Why does a custom splice function outperform native splice when the array size is lower than 3-5000?

285 Views Asked by At

I'm writing an implementation of A* path-finding for a game, and are trying to find the fastest way of inserting values into an array of integers. I've made a custom splice function, and tested it against the native one.

If the array size is below about 3-5000, the custom function outperforms the native (on chrome). The result is useful for me, because I can select the best function based on the array size, but I don't understand why native is better on larger arrays, and custom on smaller. Can you explain why?

Test is here: https://jsperf.com/native-splice-vs-custom

Custom splice function:

function splice(ary, index, value) {
    let newValue = value;
    let newIndex = index;
    let nextValue = ary[newIndex + 1];
    while(nextValue !== undefined) {
      ary[newIndex] = newValue;
      newValue = nextValue;
      nextValue = ary[++newIndex];
    }
  }
0

There are 0 best solutions below