in operator
JavaScript performance comparison
Info
Somebody asked for a benchmark here: http://webreflection.blogspot.com/2011/08/please-stop-reassigning-for-no-reason.html
However, the whole point is not about raw performances but implications that common patter to assign a potentially not defined property cause.
As example, consider it is not even possible to compare an object with a getter only since the common pattern will simply throw an Error during assignment.
obj.prop = // if no setter: ERROR
obj.prop // getter
|| {}
;
With "prop" in obj everything would be still OK.
Preparation code
<script>
// all functions should avoid JIT optimizations
// (e.g. if nothing happens JIT may nullify function body)
// hopefully assigning the object to a non GC global variable
// will do the trick ... let's see ...
function inOperator(object) {
"prop" in object || (object.prop = {});
return object;
}
function commonPattern(object) {
object.prop = object.prop || {};
return object;
}
function betterPattern(object) {
object.prop || (object.prop = {});
return object;
}
var
// simple shim that *should* fail in old browsers
// if getters/setters are not supported
defineProperty = Object.defineProperty || function (o, k, v) {
o.__defineGetter__(k, v.get);
o.__defineSetter__(k, v.set);
return o;
},
globalResult
;
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
in operator set |
|
pending… |
in operator |
|
pending… |
in operator + magic set |
|
pending… |
in operator + magic |
|
pending… |
common pattern set |
|
pending… |
common pattern |
|
pending… |
common pattern + magic set |
|
pending… |
common pattern + magic |
|
pending… |
better pattern set |
|
pending… |
better pattern |
|
pending… |
better pattern + magic set |
|
pending… |
better pattern + magic |
|
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 WebReflection
- Revision 2: published by WebReflection
0 comments