Comparing three techniques for finding items in a list

Benchmark created on


Setup

const searchList = new Array(10000).fill((v) => {
	return {
		id: `${Math.random()}`, 
		rank: Math.random()
	}	
});

const fullList =  new Array(50000).fill((v) => {
	return {
		id: `${Math.random()}`, 
		foo: Math.random(), 
		bar: Math.random(), 
		biz: Math.random(), 
		bash: Math.random(), 
	}	
});

Test runner

Ready to run.

Testing in
TestOps/sec
Use object as map
function findResults(searchResults, fullList) {
	
	const map = {}; 
	fullList.forEach(v => {
		map[v.id] = v; 
	}); 
	
	const foundResults = searchResults.reduce((acc, cur) => {
        const foundResult = map[cur.id]; 
        if (foundResult){
        	acc.push(foundResult); 
        }
        return acc;		
	}, []); 
	
	return foundResults; 
	
}


findResults(searchList, fullList); 
ready
Use map as map
function findResults(searchResults, fullList) {
	
	const map = new Map()
	fullList.forEach(v => {
		map.set(v.id, v); 
	}); 
	
	const foundResults = searchResults.reduce((acc, cur) => {
        const foundResult = map.get(cur.id)
        if (foundResult){
        	acc.push(foundResult); 
        }
        return acc;		
	}, []); 
	
	return foundResults; 
	
}


findResults(searchList, fullList); 
ready
Using indexes solution
function findResults(searchResults, fullList) {
	
	const map = new Map()
	fullList.forEach((v,i) => {
		map.set(v.id, i); 
	}); 
	
	const resultArray =[]; 
	searchResults.forEach((v) => {
		const itemIndex = map.get(v.id);
		if(itemIndex !== undefined){
				const item = fullList[itemIndex]; 
		
		resultArray.push(item); 
		} 
	
	}); 
	
	return resultArray; 
}


findResults(searchList, fullList); 
ready

Revisions

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