Why is the str[3]
version so much slower, apparently?
var str = 'Hello';
str.charAt(3);
str[3];
http://jsperf.com/charat-ck
Edit: for me, str[3]
is 80% slower on Chrome 28.0.1500.71 Ubuntu 13.04
.
Tune the benchmark a little: http://jsperf.com/charat-ck/4
Don't use constants and no-operation code like that because it can be easily eliminated and then you aren't measuring what you think you are measuring.
Next consider that even if we have infinitely smart JIT, these operations have different semantics:
What happens when you call charAt
out of bounds? Simply return the empty string.
What happens when you call []
out of bounds? Walk the prototype chain from String to Object and return undefined
when finally not found:
String.prototype[3] = "hi";
var string = "asd";
string.charAt(3); //""
string[3]; //"hi"
It is true that it could perform the same when all reads are in-bounds however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With