What's the difference between .substr(0,1) or .charAt(0)?
We were wondering in this thread if there was a real difference between the use of .substr(0,1)
and the use of .charAt(0)
when you want to get the first character (actu开发者_运维知识库ally, it could apply to any case where you wan only one char).
Is any of each faster than the other?
Measuring it is the key!
Go to http://jsperf.com/substr-or-charat to benchmark it yourself.
substr(0,1) runs at 21,100,301 operations per second on my machine, charAt(0) runs 550,852,974 times per second.
I suspect that charAt accesses the string as an array internally, rather than splitting the string.
As found in the comments, accessing the char directly using string[0] is slightly faster than using charAt(0).
Unless your whole script is based on the need for doing fast string manipulation, I wouldn't worry about the performance aspect at all. I'd use charAt()
on the grounds that it's readable and the most specific tool for the job provided by the language. Also, substr()
is not strictly standard, and while it's very unlikely any new ECMAScript implementation would omit it, it could happen. The standards-based alternatives to str.charAt(0)
are str.substring(0, 1)
and str.slice(0, 1)
, and for ECMAScript 5 implementations, str[0]
.
精彩评论