Reputation: 8759
In all the browsers I have tried so far (Firefox, Chrome, Edge), it has been significantly faster to do the following:
str.charAt(0)
Than these other two methods I've found to accomplish the same thing:
str[0]
str.substring(0, 1)
Although I can understand .substring() being significantly slower (10% of speed), isn't []
(75% of speed) with a string just a different syntax for .charAt()
?
Upvotes: 2
Views: 92
Reputation: 6622
Using an index and treating the string as an array used to be the prefered approach. charAt
was only introduced in ES5 and before IE9 you had to use string[index]
. The charAt
method is the recommended and cleaner approach to use, unless you need to support older browsers.
Presumably, it's speed comes from its predictability and the browser can optimise it a lot better than it can using an index lookup. But as you'll see in benchmarks, browsers all optimise things differently.
You will see widely different numbers in different browsers. In Chrome charAt
is faster, but in Microsoft Edge and Internet Explorer it's considerably slower and [index]
wins out (especially in IE11). Check out this JSPerf test and run it in different browsers.
Unless you're dealing with hundreds of millions of strings, you're not going to notice any slowdown using either-all. In Chrome the difference in speed is a fraction of a percentage especially.
Upvotes: 2