I have this snippet of code which I simplified for the sake of this question:
//var a is generated once at runtime
//from an array of strings
//and an array of functions
var a = [
"Start ",
function(){return "middle ";}, //returns dynamic data
"end"
],
c = "";
//this for-loop represents a call
for(var i = 0; i < a.length; i++){
var d = typeof a[i] === 'function' ? a[i]() : a[i];
c = c.concat(d);
}
console.log(c);
Now first question: Is my call (the for loop) less or more optimal than say...
var call = a[0]+a[1]()+a[2];
...where call was created at runtime somehow?
Conditional question: If the latter call is the more optimal approach then how would I go about generating this optimal call variable/object/function?
Final conditional question: If you can't figure out what I'm asking in my last question, ignore it. Instead, please tell me if my code is able to be further optimized and how?!
Edit: I went ahead and benchmarked my code by running 24M calls and the call variable is about 10% faster from my estimations.
The main answer here is: The for
loop isn't going to introduce any kind of performance penalty you'll ever notice.
But:
If a
is generated at runtime, you must have something, somewhere generating it. If so, rather than an array, why not just generate a function directly?
var acall = function() {
return "Start, " + dynamic() + "end";
};
or
var acall = function() {
return "Start, " + (function() {
return "middle ";
})() + "end";
};
The crux, really, is how a
is generated at runtime. You can usually generate functions at runtime without resorting to eval
or its cousin new Function
...
Though correct, and fine in terms of performance, this code doesn't feel right to me. What I'd do would be:
var a = [
"Start ",
function(){return "middle ";}, //returns dynamic data
"end"
];
var c = a.map(function(item) {
return typeof item === 'function' ? item() : item;
}).join('');
console.log(c);
This seems better to me than appending to your string in each for
iteration.