Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str.charAt(5) vs str[5] in Javascript

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.

like image 756
conradkleinespel Avatar asked Oct 27 '13 16:10

conradkleinespel


1 Answers

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.

like image 107
Esailija Avatar answered Oct 07 '22 05:10

Esailija