Reduce + map vs nested for

Benchmark created on


Preparation HTML


Setup

const data = [
	{
		path: [
			{
				foo: 'foo1',
				bar: 'bar1',
			},
			{
				foo: 'foo2',
				bar: 'bar2',
			},
			{
				foo: 'foo3',
				bar: 'bar3',
			}
		],
	},
];

let flattenData = [];

Test runner

Ready to run.

Testing in
TestOps/sec
reduce + map
const results = data.reduce((accumulator, current, connectionIndex) => {
	const parsedPath = current.path.map((path, pathIndex) => ({
		...path,
		'connection-name': `connection-${connectionIndex + 1}`,
		'connection-item-index': pathIndex,
    }));

    return [...accumulator, ...parsedPath];
}, []);

flattenData = flattenData.concat(results);
ready
nested for
for(let connectionIndex = 0; connectionIndex < data.length; connectionIndex++) {
	const currentPath = data[connectionIndex].path;
	
	for(let pathIndex = 0; pathIndex < currentPath.length; pathIndex++) {
		const path = currentPath[pathIndex];

		const parsedPath = {
			...path,
			'connection-name': `connection-${connectionIndex + 1}`,
            'connection-item-index': pathIndex,
		};
		
		flattenData.push(parsedPath);
	}
}
ready

Revisions

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