What's the difference between .substr(0,1) or .charAt(0)?

后端 未结 2 1735
北恋
北恋 2021-01-08 00:54

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

相关标签:
2条回答
  • 2021-01-08 01:24

    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).

    0 讨论(0)
  • 2021-01-08 01:34

    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].

    0 讨论(0)
提交回复
热议问题