在Javascript中str.charAt(5)vs str [5]

con*_*com 6 javascript performance

为什么str[3]版本显然要慢得多?

var str = 'Hello';

str.charAt(3);
str[3];
Run Code Online (Sandbox Code Playgroud)

http://jsperf.com/charat-ck

编辑:对我而言,str[3]慢了80%Chrome 28.0.1500.71 Ubuntu 13.04.

Esa*_*ija 4

稍微调整基准: http: //jsperf.com/charat-ck/4

不要使用这样的常量和无操作代码,因为它很容易被消除,然后您就无法测量您认为正在测量的内容。

接下来考虑一下,即使我们有无限智能的 JIT,这些操作也有不同的语义:

charAt当您越界呼叫时会发生什么?只需返回空字符串即可。

[]当您越界呼叫时会发生什么?将原型链从 String 遍历到 Object,并undefined在最终找不到时返回:

String.prototype[3] = "hi";
var string = "asd";
string.charAt(3); //""
string[3]; //"hi"
Run Code Online (Sandbox Code Playgroud)

然而,当所有读取都在范围内时,它确实可以执行相同的操作。