Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How efficient is the "with" statement?

It is hard to Google for some keywords like "with" word, so I am testing to ask here.

Is the with statement in JavaScript inefficient?

For instance, say I have:

with(obj3) {
     with(obj2) {
         with(obj1) {
               with(obj0) {
                    eval("(function() { console.log(aproperty) })();");
               }
         }
     }
}

Would the above be more or less efficient, if for instance, I walked over obj0, obj1, obj2, obj3 and merged them together, and then used either:

  1. One with statement alone
  2. Created a parameters string with the keys of obj0, obj1, obj2 and obj3, and an args array for the values and used:

    eval("function fn(aproperty, bproperty) { console.log(aproperty); }")
    fn.apply(undefined, args);
    

Which of these three approaches can be deemed to be quicker? I am guessing on with statements but so many with's makes me think I can optimize it further.

like image 591
mjs Avatar asked Feb 02 '26 18:02

mjs


1 Answers

If you're looking for options, then you may want to consider a third approach, which would be to create (on the fly if needed) a prototype chain of objects.


EDIT: My solution was broken. It requres the non-standard __proto__ property. I'm updating to fix it, but be aware that this isn't supported in all environments.


var objs = [null,obj3,obj2,obj1,obj0];

for (var i = 1; i < objs.length; i++) {
    objs[i].__proto__ = Object.create(objs[i-1]);
}

var result = objs.pop();

This avoids with and should be quicker than merging, though only testing will tell.


And then if all you needed was a product of certain properties, this will be very quick.

var props = ["x2","b1","a3"];
var product = result.y3;

for (var i = 0; i < props.length; i++)
    product *= result[props[i]];
like image 123
5 revsBlue Skies Avatar answered Feb 05 '26 06:02

5 revsBlue Skies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!