Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster to access numeric property by string or integer?

In JavaScript you can get and set indexes of arrays and "numeric" properties of objects using either an integer or a string and get the same results:

var a=[], o={};
a[1]    = "foo";  a["1"]   == "foo" // true
a["2"]  = "bar";  a[2]     == "bar" // true
a["-3"] = "baz";  a[-.3e1] == "baz" // true
o[1]    = "foo";  o["1"]   == "foo" // true
o["2"]  = "bar";  o[2]     == "bar" // true
o["-3"] = "baz";  o[-.3e1] == "baz" // true

While strings and numbers are interopable—for both getting and setting—which is faster (for both arrays and for objects)?

like image 290
Phrogz Avatar asked May 17 '12 16:05

Phrogz


People also ask

What is difference between numeric and string index array?

The answer is simple: there is no difference. Javascript arrays are objects. All keys of objects are strings (or symbols), but never numbers.

Can a string be a key in an object?

Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.

Can numbers be keys in object JavaScript?

Each key in your JavaScript object must be a string, symbol, or number.


1 Answers

Unsurprisingly, integers are faster for array access than strings. Perhaps surprisingly, they are also faster than strings for object properties.

http://jsperf.com/string-vs-integer-array-indices

enter image description here

http://jsperf.com/string-vs-integer-object-indices

enter image description here

like image 152
Phrogz Avatar answered Sep 28 '22 17:09

Phrogz