Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is string comparison faster than string length?

I am unsure of which of these ways is faster to use multiple times, testing with a lot of string variables.
Which of these is faster to use for checking if the string is just whitespace?

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

}

Or

if (str.trim() !== '') {

}
like image 594
jackcogdill Avatar asked Dec 11 '22 17:12

jackcogdill


2 Answers

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

In terms of calculations per second, they differ by less than 1% (at least on Chromium). Unless you're testing millions of strings every second, I wouldn't worry about it.

like image 172
Blender Avatar answered Dec 30 '22 08:12

Blender


The short answer is "benchmark and find out!". If you do this, you can also try using a regexp and see how fast that is:

if (str.match(/^\s*$/))
like image 30
Alex D Avatar answered Dec 30 '22 09:12

Alex D