开发者

Performance & "Better Practice": with statement vs. function with a bunch of parameters

I've been doing a lot of templating in JS lately, so I've invariably run across the "evil" with statement.

It makes templates much easier to work with as you don't have to preface your variables with an object.

Hearing that with statements are bad and also that they may cause poor performance, I set out for another solution:

My Solution: Function with a bunch of parameters

Here's my code:

开发者_C百科
var locals = {
  name : "Matt",
  email : "wahoo@wahoo.com",
  phone : "(555) 555-5555"
};

var keys = [];
var values = [];

for (key in locals) {
  local = locals[key];

  keys.push(key)
  values.push(local);

}

keys = keys.join(',');

var fn = new Function(keys, "**TEMPLATE STUFF**"); // function(name, email, phone) {...}
fn.apply(this, values); // fn("Matt","wahoo@wahoo.com","(555) 555-5555")

Note: these accomplish the exact same thing. Both are abstracted away from anyone so an obnoxiously long parameter list is no biggie.

I'm wondering which one is better: using a with statement or a function with the potential for a crazy number of parameters.

Unless someone has a better solution...?

Thanks! Matt Mueller


I find your solution very bloated. It is totally non-trivial, while with is so simple (one line of code which in and of itself has very little cost vs. your object traversal and array instantiations). Moreover, your solution requires a template object ready when making the templating function (to define its parameters), which may prove down the road less flexible in my opinion.

Check out MDC. A well designed template would presumably have little logic and heavy variable references (and if it isn't that way, then it should be!), which makes with the perfect candidate in such a situation, because there should be very few other lookups in the scope of the with.

Any extra performance that may be gained seems like it would be micro-optimisation, although rather than theorise, just perform some benchmarks. http://jsperf.com/with-vs-fn does all the setup code before the benchmark for your version, but performs the with stuff during the function execution, so it's not really fair, although even on the slowest iterations you get an idea of how fast it is; >400,000 ops/sec is the slowest. I doub't you need to render more than 400,000 templates a second...


Have you tried a JS templating engine? They are usually very fast, and save you some rendering code.

I'm the author of pure.js which is a bit original, but there are plenty of others available and for any taste.


The problems with with are not performance, they are ambiguity and unpredictable behaviour.

See, for example, Hidden Features of JavaScript?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜