admin管理员组

文章数量:1208155

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)?

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)?

Share Improve this question edited Jul 15, 2013 at 12:34 holographic-principle 19.7k10 gold badges47 silver badges62 bronze badges asked May 17, 2012 at 16:16 PhrogzPhrogz 303k113 gold badges667 silver badges756 bronze badges 9
  • The key can actually be anything, not just an integer or string. – Mike Christensen Commented May 17, 2012 at 16:19
  • 1 @MikeChristensen not entirely true, other objects are converted to strings. To demonstrate it: var o={},a=[];o[a]=2;alert(o[""]) – Lekensteyn Commented May 17, 2012 at 16:21
  • 3 Is a micro-optimization question really getting this many upvotes? – JohnFx Commented May 17, 2012 at 16:24
  • 1 @JuanMendes You can also argue that strings are converted to integers if possible. var a=[];a["42"]=1;a.length==43 – Lekensteyn Commented May 17, 2012 at 16:25
  • 1 @JohnFx It's very likely that this is micro optimization, but it's fun. If you really want fast array access, use developer.mozilla.org/en/JavaScript_typed_arrays – Ruan Mendes Commented May 17, 2012 at 16:29
 |  Show 4 more comments

1 Answer 1

Reset to default 26

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

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

本文标签: javascriptFaster to access numeric property by string or integerStack Overflow