This week i was writing some JavaScript easy script for mirroring data. Main job was work wit data in arrays. I was reading data from arrays, make some calculations with data from there and that is it. Easy.
In first implementation i was using array as structure for manipulation with data. And then I was try rewrite manipulation with data to Set.
Tests
Finally i wrote some simple tests for comparing both ways of implementations. I made array and Set of 1.000.000 items and i tried some basic operations on those.
Results
array | Set | |
creating | 25.40 ms | 128.72 ms |
iterating through | 4.24 ms | 34.72 ms |
finding | 1.01 ms | 0.01 ms |
Source code
array
const { performance } = require('perf_hooks'); const arrayLength = 1000000; // creating array console.log('CREATING TEST'); let start = performance.now(); const items = []; for (let i = 0; i < arrayLength; i++) { items.push(i); } console.log(performance.now() - start); console.log('END TEST\n'); // iteration over array console.log('ITERATION TEST'); let sum = 0; start = performance.now(); for (let i = 0; i < arrayLength; i++) { sum += items[i]; } console.log(performance.now() - start); console.log(`summ = ${sum}`); console.log('END TEST\n'); // findig in array console.log('FINDING TEST'); start = performance.now(); if (items.includes(arrayLength - 1)) console.log('OK'); console.log(performance.now() - start); console.log('END TEST\n');
Set
const { performance } = require('perf_hooks'); const arrayLength = 1000000; // xreating array console.log('CREATING TEST'); let start = performance.now(); const items = new Set(); for (let i = 0; i < arrayLength; i++) { items.add(i); } console.log(performance.now() - start); console.log('END TEST\n'); // iteration over array console.log('ITERATION TEST'); let sum = 0; start = performance.now(); items.forEach(i => { sum += i; }); console.log(performance.now() - start); console.log(`summ = ${sum}`); console.log('END TEST\n'); // finding in set console.log('FINDING TEST'); start = performance.now(); if (items.has(arrayLength - 1)) console.log('OK'); console.log(performance.now() - start); console.log('END TEST\n');