Creating a Map from an array using forEach vs reduce

Benchmark created on


Description

Goal: Creating a new Map

We will compare the performance of forEach vs reduce.

Setup

var count = 1000000;

var array = Array(count).fill(undefined).map(x => ({
	id: Math.random().toString(),
	name: Math.random().toString(),
	hello: 'qwerty',
	world: 'qwerty',
	this: 'qwerty',
	is: 'qwerty',
	a: 'qwerty',
	test: 'qwerty'
}));

Test runner

Ready to run.

Testing in
TestOps/sec
Creating the Map using forEach
const map = new Map();

array.forEach(el => {
	map.set(el.id, el);
});
ready
Creating the Map using reduce
const map = array.reduce((acc, el) => {
	return acc.set(el.id, el);
}, new Map());
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.