map-filter-or-reduce (v8)

Revision 8 of this benchmark created on


Setup

window.arr = new Array(10000).fill(0).map((_,i) => i)

Test runner

Ready to run.

Testing in
TestOps/sec
filter+map
const newArr = window.arr.filter(x=>x%2).map(x=>2*x)
ready
reduce-only
const newArr = window.arr.reduce((acc, val) => {
	if(val%2) {
		return [...acc, val*2]
	}
	return acc
},[])
ready
reduce-only-v2
const newArr = window.arr.reduce((acc, val) => {
	if(val%2) {
		acc.push(val*2); // `Array.prototype.push` returns `.length`.
		return  acc;
	}
	return acc;
},[])
ready
reduce-only-v3
const newArr = window.arr.reduce((acc, val) => {
	if(val%2) {
		return ( acc.push(val*2), acc ); // NOTE: This uses the comma-operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator
	}
	return acc;
},[])
ready
reduce-only-v3
const newArr = window.arr.reduce((acc, val) => {
	return ( val % 2 ) ? ( acc.push(val*2), acc ) : acc;
},[])
ready
reduce-only-v3.5
const newArr = window.arr.reduce( (acc, val) => ( val % 2 ) ? ( acc.push(val*2), acc ) : acc, /*seed:*/ [] );

ready
for
const newArr = [];
for( let i = 0; i < window.arr.length; i++ ) {
	if( window.arr[i] % 2 ) newArr.push( window.arr[i] );
}
ready
for-of
const newArr = [];
for( const a of window.arr ) {
	if( a % 2 ) newArr.push( a );
}
ready
Array.prototype.forEach v1
const newArr = [];
window.arr.forEach( function( e ) {
	if( e % 2 ) newArr.push( e );
} );
ready
Array.prototype.forEach v2 - Phat arrow stylin'
const newArr = [];
window.arr.forEach( e => {
	if( e % 2 ) newArr.push( e );
} );
ready

Revisions

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