‘with’ or without?
September 6th, 2007 by kangax
(Permalink)
I remember back in the days there were these huge articles about refactoring Javascript to perform faster. “with” statements were considered a huge slow down…
Just to satisfy my curiosity I rolled a quick test:
Foo = { Bar: { Baz: { Qux: { Quux: function(){} } } } } // Plain call console.time('test'); for (var i=0; i<100000; ++i) { Foo.Bar.Baz.Qux.Quux(); } console.timeEnd('test'); // 562 ms // "with" outside the loop console.time('test'); with(Foo.Bar.Baz.Qux) { for (var i=0; i<100000; ++i) { Quux(); } } console.timeEnd('test'); // 359 ms // with inside the loop console.time('test'); for (var i=0; i<100000; ++i) { with(Foo.Bar.Baz.Qux) { Quux(); } } console.timeEnd('test'); // 1891 ms // aliasing console.time('test'); for (var i=0, q=Foo.Bar.Baz.Qux.Quux; i<100000; ++i) { q(); } console.timeEnd('test'); // 422 ms
fearphage said:
#Although this is similar, it is not actually using the with statement.
with (Foo.Bar.Baz) {for (var i = 0; i < 100000; i++) {
Quux();
}
}
Tobie Langel said:
#The with statement is especially expensive in IE.
eyelidlessness said:
#Reposted with <, > and & escaped…
This is not testing the aspect of
with()that is actually slow, which is when you reference objects in awith()block that are not in the object passed as an argument towith().var zig = function() {}; console.time('test'); with(Foo.Bar.Baz.Qux) { for (var i=0; i<1000000; ++i) { zig(); Quux(); } } console.timeEnd('test'); // 470ms (avg of 3) console.time('test'); for (var i=0; i<1000000; ++i) { zig(); Foo.Bar.Baz.Qux.Quux(); } console.timeEnd('test'); // 438 ms (avg of 3)It’s not a huge difference, but it is a difference. With that said, the benefits of
with()are greater if you are vigilant to only use properties descending from the object passed towith().eyelidlessness said:
#Well, it’s good to know that
<pre>blocks are recommended for posting code sections, render great on the client-side preview, but are stripped when posted. That’s… helpful.http://i45.tinypic.com/2qnbn2f.jpg
kangax (article author) said:
#@eyelidlessness
Jeez, sorry about that, I fixed your comment. It worked fine last time I checked. Will need to see why they get stripped now.
I’ll respond to a comment as soon as I get a chance.