4

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?

stinkycheeseman
  • 43,437
  • 7
  • 30
  • 49
  • 2
    You can do your own test on http://jsperf.com – Andreas Louv Jul 06 '12 at 17:55
  • 1
    It likely would, yes. But just test it... it's not hard to make tests for. – TheZ Jul 06 '12 at 17:55
  • If you're interested in performance, you'd b better off pulling the operator testing out of the loop completely, if possible. (Your example code doesn't show "operator" changing in the loop.) – Pointy Jul 06 '12 at 17:56
  • I wouldn't have thought there'd be a big difference. However, since your function is a method, a simple optimisation would be to create a reference to it in a local variable, as these are quicker for JS to resolve than object methods. – Mitya Jul 06 '12 at 17:57
  • possible duplicate of [JavaScript: "Function calls are expensive" vs. "Keep functions small"](http://stackoverflow.com/questions/11168939/javascript-function-calls-are-expensive-vs-keep-functions-small) – Tomasz Nurkiewicz Jul 06 '12 at 17:57

2 Answers2

2

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!

Phillip Schmidt
  • 8,805
  • 3
  • 43
  • 67
1

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.

stinkycheeseman
  • 43,437
  • 7
  • 30
  • 49