I have a little bit of code that looks just like this:
function StrippedExample(i1, i2, i3, i4, i5, i6, i7, i8) {
this.i = [];
for (var i=1,j=0 ;i<9;i++) {
var k = eval("i"+i);
if (k > 0) {
this.i[j++] = k;
}
}
}
FireBug profiler claims that second longest function is eval(), taking up to nearly 6% of the run time.
Everyone says eval is EVIL (as in bad) and slow (as I have found), but I can’t really do anything else – the server simply pulls the data out the database and pushes to the browser.
What alternatives do I have? I could do the same as I am doing here on the server but that just shifts the burden higher up the chain. I can’t change the database layout since everything hooks into those 8 variables and is a massive undertaking.
The above code can be simplified further, I just made the minimal change to get rid of
eval. You can get rid ofj, for example:is equivalent. Or, to use the built-in
argumentsobject (to avoid having your parameter list in two places):Even if you weren’t filtering the list, you don’t want to do something like
this.i = argumentsbecauseargumentsis not a real Array; it has acalleeproperty that you don’t need and is missing some array methods that you might need ini. As others have pointed out, if you want to quickly convert theargumentsobject into an array, you can do so with this expression:You could use that instead of the
var args = [i1, i2 ...lines above.