Skip to content

Instantly share code, notes, and snippets.

@iamcsharper
Created May 14, 2022 17:15
Show Gist options
  • Save iamcsharper/1aec9c2ed58ec4f930dd64e0b33b3d67 to your computer and use it in GitHub Desktop.
Save iamcsharper/1aec9c2ed58ec4f930dd64e0b33b3d67 to your computer and use it in GitHub Desktop.
JS Map population performance
const functionOne = () => {
const data = Array.from(Array(2000).keys());
const a = new Map();
data.forEach(e => {
a.set(e, {value: e + 1});
});
return [...a.values()];
};
const functionTwo= () => {
const data = Array.from(Array(2000).keys());
const a = new Map(data.map(e => (
[e, {value: e + 1}]
)));
return [...a.values()];
};
const functionThree= () => {
const data = Array.from(Array(2000).keys());
const a = new Map();
for (let i = 0; i < data.length; i++) {
const e = data[i];
a.set(e, {value: e + 1});
}
return [...a.values()];
};
var iterations = 100000;
console.time('Function #1');
for(var i = 0; i < iterations; i++ ){
functionOne();
};
console.timeEnd('Function #1')
console.time('Function #2');
for(var i = 0; i < iterations; i++ ){
functionTwo();
};
console.timeEnd('Function #2')
console.time('Function #3');
for(var i = 0; i < iterations; i++ ){
functionThree();
};
console.timeEnd('Function #3')
@iamcsharper
Copy link
Author

iamcsharper commented May 14, 2022

Top:
Function #3 (for): 13.600s (7352.94118 ops/sec)
Function #1 (array forEach): 13.843s (7223.86766 ops/sec)
Function #2 (map to entries): 19.523s (5122.1636 ops/sec)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment