Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript change string case speed

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

like image 658
Timothy Ruhle Avatar asked Mar 01 '11 05:03

Timothy Ruhle


1 Answers

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.

like image 89
Cᴏʀʏ Avatar answered Sep 20 '22 15:09

Cᴏʀʏ