In my last article, I gave a brief of time complexities of some popular Javascript array methods. In this article, I will give three code examples of how to improve the performance in array solutions.

Below are examples of O(n*2) solutions to common array problems. We will explore other options for solving with the aim of improving performance.

Example One: Return Duplicate Elements in an Array.

Problematic: For each element, loop through the array to see if there is another element like it. If yes, push to another array, if no, don’t.

GitHub Gist with less performant code

The above solution is O(n*2). For every first element in the array, we take another loop through the array to find if it has a match. For a few elements, it may not be slow, but as you increase the items (i.e 100k elements) you begin to see the slowness.

Performant: Create a map, loop through array and check map, if map has element already, push to return array.

#performance #arrays #javascript #big-o-notation

Javascript Arrays: From O(n*2) to O(n) — Code Examples
3.00 GEEK