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

Why is the version of str[3] 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 .

+6
source share
1 answer

Set up the test a bit: http://jsperf.com/charat-ck/4

Do not use constants and code without an operation, because it can be easily eliminated, and then you do not measure what you think you are measuring.

Further, we consider that even if we have an infinitely smart JIT, these operations have different semantics:

What happens when you call charAt out of bounds? Just return the empty string.

What happens when you call [] outside? Go through the prototype chain from String to Object and return undefined when you finally don't find:

 String.prototype[3] = "hi"; var string = "asd"; string.charAt(3); //"" string[3]; //"hi" 

It is true that he could do the same thing if all readings are related.

+3
source

Source: https://habr.com/ru/post/956824/


All Articles