What do you want to use it for? – 2 minute read


I’m always working to improve my code.   One of the ways that I do this is that I frequently work on Code Wars practice problems.  I was working on a  prime number generator  for a practice problem (if  you’re interested, the code is here:
https://github.com/tmurphree/node-utilities/blob/master/primeNumberGenerator.js)  and I wondered, “Should I use a set or an array?”


I solved the problem with both a set and an array, and I ran some tests* to see how long the function took to run and how long the searches on the results took.   The results were interesting:



Operation Average time (ms)
Array generation 18.2412
Set generation 44.3016
Array seek 0.021
Set seek 0.0099

The set took about 2.4x the time to generate as the array, but it is searchable in about 1/2 the time.  So the answer to the question “Should I use a set or an array?” boils down to another question: "What do you want to use it for?"

If you want to use native array functions or if getting a fast start is important, use an array.

If you want to reuse a large set and seek time is important, use a set. 

* I ran 10 iterations of finding primes under 50,000 and then searching for 48,539.  I used console.time() to time the runs.

Comments

Popular posts from this blog

Optional object property access

A short guide to cross-site request forgery attacks

How is an application like a bride's outfit? - 1 minute read