String comparison faster than line length?

I'm not sure which of these methods is faster to use several times, testing many variables. Which one is faster to use to check if the string is just whitespace?

if (str.trim().length > 0) { } 

or

 if (str.trim() !== '') { } 
+4
source share
5 answers

OK, why not test it? http://jsperf.com/empty-string-comparison2

In calculations per second, they differ by less than 1% (at least from chromium). If you do not test millions of lines every second, I would not worry about that.

+7
source

The short answer is "test and find out!". If you do this, you can also try using a regular expression and see how fast this happens:

 if (str.match(/^\s*$/)) 
+2
source

According to this quick test, the regex suggested by Alex D is faster.

 string = " lll sfsf __ "; d = new Date().getTime(); for(var i = 0; i < 900000; i++){ if (string.trim().length > 0) continue; } d1 = new Date().getTime() - d; alert(d1); d = new Date().getTime(); for(var i = 0; i < 900000; i++){ if (string.trim() !== '') continue; } d1 = new Date().getTime() - d; alert(d1); d = new Date().getTime(); for(var i = 0; i < 900000; i++){ if (string.match(/^\s*$/)) continue; } d1 = new Date().getTime() - d; alert(d1); 
+2
source

I find String Lenght comparing faster than comparing two strings.

+1
source

JSFiddle: http://jsfiddle.net/pja77gzp/

 <script> var s1 = ' '; var s2 = ' '; var benchmarkCount = 10000000; function testStringComparison() { var t = new Date(); var i = 0; for (var i = 0; i < benchmarkCount; i++) { if (s1.trim().length == s2.trim().length) { i++; } } t = (new Date()) - t; document.writeln("testStringComparison completed"); document.writeln(t); } function testStringLenght() { var t = new Date(); var i = 0; for (var i = 0; i < benchmarkCount; i++) { if (s1.trim() == s1.trim()) { i++; } } t = (new Date()) - t; document.writeln("testStringLenght completed"); document.writeln(t); } function startBenchmark() { testStringComparison(); testStringLenght(); } setTimeout(startBenchmark, 1000); </script> 
+1
source

All Articles