0

An example of what I'm talking about.

This implementation, is much faster..

var data = [1, 2, 3, 4];
var currIndex = 0;
var copied = [];
for (var i = 0; i < data.length; i++) {
  copied[currIndex] = data[i];
  currIndex++;
}

Than this:

var data = [1, 2, 3, 4];
var copied = [];
for (var i = 0; i < data.length; i++) {
  copied.push(data[i]);
}

It's obvious that when writing JS, most people would write the second implementation as it's clearer what they're doing. Plus, with the first one, you are re-inventing the wheel.

Not sure why JS functions are so expensive.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
TLE
  • 19
  • 2
  • 1
    `copied.push(data[i);` isn’t valid. – Sebastian Simon Aug 19 '16 at 02:46
  • 1
    Define "much faster". "why JS functions are so expensive" --- *expensive* compared to *what*? – zerkms Aug 19 '16 at 02:47
  • 2
    Related: [Why is `array.push` sometimes faster than `array[n] = value?`](http://stackoverflow.com/q/614126/4642212) and [Is there a reason JavaScript developers don’t use `Array.push()`?](http://stackoverflow.com/q/15649899/4642212). – Sebastian Simon Aug 19 '16 at 02:49
  • @Xufox yes it is... – TLE Aug 19 '16 at 03:00
  • Inlining an operation is often faster than calling a function that does that operation. `copied[currIndex] = data[i];` is inlining the operation rather than calling a function. Same in lots of languages. Plus, `.push()` may have some error checking on it that you do not. You would expect `obj.i++` to be faster than `obj.increment(i)` right? – jfriend00 Aug 19 '16 at 03:01
  • 1
    Is your question "why are functions slower", or "why do people use functions even though they're slower"? –  Aug 19 '16 at 03:21
  • Related: [Javascript for..in vs for loop performance](http://stackoverflow.com/questions/13645890/javascript-for-in-vs-for-loop-performance) and: [Why is using “for…in” with array iteration a bad idea](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Mehdi Dehghani Aug 19 '16 at 03:22

0 Answers0