map to filtered list

Benchmark created on


Description

Compare creating a list out of map values and filter that list, vs populating via the iterator protocol

Setup

const theMap = new Map()
new Array(10000)
  .fill()
  .map((_, i) => 20000 - i)
  .forEach((v, i) => theMap.set(i, v))
  
const slice1 = [0, 2500]
const slice2 = [2501, 5000]
const slice3 = [5001, 7500]
const slice4 = [7501, 10000]

Test runner

Ready to run.

Testing in
TestOps/sec
values to list, then filter
const values = [...theMap.values()]

const group1 = values.filter(
  v => v >= slice1[0] && v <= slice1[1]
)
const group2 = values.filter(
  v => v >= slice2[0] && v <= slice2[1]
)
const group3 = values.filter(
  v => v >= slice3[0] && v <= slice3[1]
)
const group4 = values.filter(
  v => v >= slice4[0] && v <= slice4[1]
)

ready
iterate values to lists
const group1 = []
const group2 = []
const group3 = []
const group4 = []

for (const v of theMap.values()) {
	if (v >= slice1[0] && v <= slice1[1]) {
		group1.push(v)
	} else if (v >= slice2[0] && v <= slice2[1]) {
		group2.push(v)
	} else if (v >= slice3[0] && v <= slice3[1]) {
		group3.push(v)
	} else if (v >= slice4[0] && v <= slice4[1]) {
		group4.push(v)
	}
}
ready
iterate with pre-alloc
const group1 = new Array(250)
const group2 = new Array(250)
const group3 = new Array(250)
const group4 = new Array(250)

let i1 = 0, i2 = 0, i3 = 0, i4 = 0

for (const v of theMap.values()) {
	if (v >= slice1[0] && v <= slice1[1]) {
		group1[i1++] = v
	} else if (v >= slice2[0] && v <= slice2[1]) {
		group2[i2++] = v
	} else if (v >= slice3[0] && v <= slice3[1]) {
		group3[i3++] = v
	} else if (v >= slice4[0] && v <= slice4[1]) {
		group4[i4++] = v
	}
}
ready

Revisions

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