1 line change, 12x speed improvement - Why profiling is important!

Sometimes it's the most unexpected lines of code that contributes to slow performance. Take this line for example; [this.heapArray[j], this.heapArray[k]] = [this.heapArray[k], this.heapArray[j]]; Nice, succinct and readable way to swap two elements in an array, using the modern destructuring syntax. Here's a performance benchmark comparison between heap-js - a package that uses this syntax, and heap - a different package implemented differently but does the same thing. heap-js blows the time scale for the same operations!! Now let's change that one line to this good old fashioned temp-variable approach: const temp = this.heapArray[j]; this.heapArray[j] = this.heapArray[k]; this.heapArray[k] = temp; and let's re-test the performance comparison: Wow!! We went from 68.08ms for the highest x-value to 5.59ms?! How? Now's my time to preach about profiling

Apr 28, 2025 - 14:13
 0
1 line change, 12x speed improvement - Why profiling is important!

Sometimes it's the most unexpected lines of code that contributes to slow performance. Take this line for example;

 [this.heapArray[j], this.heapArray[k]] = [this.heapArray[k], this.heapArray[j]]; 

Nice, succinct and readable way to swap two elements in an array, using the modern destructuring syntax.

Here's a performance benchmark comparison between heap-js - a package that uses this syntax, and heap - a different package implemented differently but does the same thing.

Heap-js vs heap performance comparison.

heap-js blows the time scale for the same operations!!

Now let's change that one line to this good old fashioned temp-variable approach:

    const temp = this.heapArray[j];
    this.heapArray[j] = this.heapArray[k];
    this.heapArray[k] = temp;

and let's re-test the performance comparison:

Heap-js vs heap performance comparison after change.

Wow!! We went from 68.08ms for the highest x-value to 5.59ms?!

How?

Now's my time to preach about profiling