Which is faster? toUpperCase() or toLowerCase() in javascript?
Here are some test results from major browsers (several months old). It comes to the conclusion that toLowerCase()
is faster, but there are no insights into why provided.
EDIT:
I have gone and looked through the WebKit JavaScript source code just out of curiosity. The .toUpperCase()
and .toLowerCase()
prototype methods are identical except for some calls to .toASCIIUpper()
, .toASCIILower()
, and Unicode::toUpper()
and Unicode::toLower()
. Further inspecting the first two methods, I saw that the .toLowerCase()
function is slightly less complex than the .toUpperCase()
function.
.toASCIILower()
does some simple bit shifting logic:
char toASCIILower(char c) {
return c | ((c >= 'A' && c <= 'Z') << 5);
}
.toASCIIUpper()
is a tad bit more involved:
char toASCIIUpper(char c) {
return static_cast<char>(c & ~((c >= 'a' && c <= 'z') << 5));
}
The static cast and extra bitwise negation (~) in the .toASCIIUpper()
function, repeated over a million iterations, could perhaps account for its poorer performance.
Now, this is all speculative; I've done no real testing nor have I tried to fully understand these methods, but maybe somebody else can elaborate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With