Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the efficiency of javascript .toUpperCase method?

So this seems like a super basic question, but I'm wondering about javascript's built in .toUpperCase() method- is the time efficiency O(n) or O(1)?

I always just assumed it would be constant time, but now that I think about it ... "under the hood" wouldn't this method need to go through each character to check if it is lower case one by one? (therefore making it O(n)

like image 567
Aljosha Novakovic Avatar asked Sep 12 '25 10:09

Aljosha Novakovic


1 Answers

The algorithm described in String.prototype.toLowerCase ( ) of the specification is O(n). Each codepoint of the original String (or String representation of the original object) is copied and converted to a new codepoint.

The fact that toUpperCase and toLowerCase return new Strings (because JavaScript Strings are immutable) is enough to verify that the operation takes linear time, not constant.

like image 195
Bill the Lizard Avatar answered Sep 13 '25 23:09

Bill the Lizard