Beware of implicit object conversion
JavaScript performance comparison
Info
Taken from: http://dev.opera.com/articles/view/efficient-javascript/
Literals, such as strings, numbers, and boolean values, have two representations within ECMAScript. Each of them can be created as either a value or an object. For example, a string value is created simply by saying var oString = 'some content';, while an equivalent string object is created by saying var oString = new String('some content');. Any properties and methods are defined on the string object, not the value. When you reference a property or method of a string value, the ECMAScript engine must implicitly create a new string object with the same value as your string, before running the method. This object is only used for that one request, and will be recreated next time you attempt to use a method of the string value. This example requires the script engine to create 21 new string objects, once for each time the length property is accessed, and once each time the charAt method is called: var s = '0123456789'; for( var i = 0; i < s.length; i++ ) { s.charAt(i); } This equivalent example creates just a single object, and will perform better as a result: var s = new String('0123456789'); for( var i = 0; i < s.length; i++ ) { s.charAt(i); } If your code calls methods of literal values very often, you should consider converting them into objects instead, as in the previous example. Note that although most of the points in this article are relevant to all browsers, this particular optimization is aimed mainly at Opera. It may also affect some other browsers, but can be a little slower in Internet Explorer and Firefox.
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
simple string |
|
pending… |
new String object |
|
pending… |
String object |
|
pending… |
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
- Revision 1: published by Matthew O'Donoghue
- Revision 2: published
- Revision 3: published by Kyle Simpson
- Revision 4: published
- Revision 5: published by Krzysztof Kula
- Revision 6: published by Kyle Simpson
- Revision 7: published by Krzysztof Kula
- Revision 8: published
- Revision 9: published by XP1
- Revision 10: published by gfx
1 comment
Be wary that String() does not cast primitive to object, it just makes a type casting: