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

后端 未结 2 1752
北恋
北恋 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).

提交回复
热议问题