Reputation: 45787
I am iterating through a large array (10^5 items) and performing an operation on each.
for (var row in rows) {
switch (operator) {
case "op1":
row += 1;
break;
case "op2":
...
case "opN":
break;
}
}
For testability and readability, I would like to extract that inner switch statement to it's own function, so the loop merely looks like
for (var row in rows) {
this.updateRow(row, operator);
}
Will the overhead associated with calling a function 10^5 times cause a noticeable performance penalty?
Upvotes: 4
Views: 118
Reputation: 45787
Yes
Using JSPerf I profiled my example here: http://jsperf.com/inline-switch-vs-switch-function
I tested the inline switch statement with 4 simple arithmetical operators against an identical switch statement extracted to it's own function over an array with 100k items. I also tested it using a randomized switch operator, best case operator (first switch option), and worst case operator (last switch option).
The inline switch statement outperformed the function across the board, beating the function by ~150 ops/sec in the worst case, ~600 ops/sec in the best case.
In this situation, the inline switch statement would be noticeably faster.
Upvotes: 1
Reputation: 8818
Inline functions are always going to be a liiiitle bit faster than defined ones. This is because things like parameters and returns don't need to be pushed and popped from the stack at runtime. Usually this isn't much of an issue with newer machines, but with 10^5 function calls you could see a little bit of a performance hit.
I'd probably keep it inline. Doesn't really hurt much, and every little bit of optimization helps!
Upvotes: 2