Javascript string change rate

Which is faster? toUpperCase () or toLowerCase () in javascript?

+7
source share
4 answers

Here are some test results from major browsers (a few months ago). He concludes that toLowerCase() is faster, but there is no understanding of why this is provided.

EDIT:

I went and looked at the source code of WebKit JavaScript just out of curiosity. The prototype methods .toUpperCase() and .toLowerCase() identical, with the exception of some calls to .toASCIIUpper() , .toASCIILower() and Unicode::toUpper() and Unicode::toLower() . Further, checking the first two methods, I saw that the .toLowerCase() function is a little less complicated than the .toUpperCase() function.


.toASCIILower() performs some simple bit offset logic:

 char toASCIILower(char c) { return c | ((c >= 'A' && c <= 'Z') << 5); } 

.toASCIIUpper() bit more complicated:

 char toASCIIUpper(char c) { return static_cast<char>(c & ~((c >= 'a' && c <= 'z') << 5)); } 

Static addition and incremental bitwise negation (~) in the .toASCIIUpper() function, repeated over a million iterations, could explain its lower performance.

Now this is all speculative; I did not conduct any real tests, and I did not try to fully understand these methods, but maybe someone else can develop.

+13
source

According to tests , the website says

toLowerCase() is faster than toUpperCase()

+3
source

They must be the same. Perhaps they can be optimized for the case when all characters already have upper / lower case, but then it will depend on in which case the string is already found, for example. 'abc'.toLowerCase() will be faster than 'abc'.toLowerCase() because it does not need to highlight a new line. I do not know any implementations that do this.

Indeed, the only way to find out is to test both functions with different lines.

+2
source

Here are my test results.

Browser: Google Chrome

OS: Ubuntu

toLowerCase: 19.68 seconds

toUpperCase: 20.71 seconds

 <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=100000000;i++) { "some string".toUpperCase(); //"SOME STRING".toLowerCase(); } document.write("done!"); </script> </body> </html> 
+1
source

All Articles