Skip to content

Instantly share code, notes, and snippets.

@caderek
Last active September 29, 2021 20:07
Show Gist options
  • Select an option

  • Save caderek/b0c376c9606050acc58232aa07442643 to your computer and use it in GitHub Desktop.

Select an option

Save caderek/b0c376c9606050acc58232aa07442643 to your computer and use it in GitHub Desktop.
Manipulating the array - JS benchmark
import b from "benny"
import cloneDeep from "clone-deep"
const testData = new Array(3000).fill(null).map((val, i) => ({
if: i,
currDate: Math.round(Math.random() * 1e10),
name: Math.round(Math.random() * 1e10).toString(16),
someString: Math.round(Math.random() * 1e10).toString(16),
foo: "foo",
bar: "bar",
baz: "baz",
}))
b.suite(
"Manipulating the array",
b.add("sort -> filter -> map (mutates!)", () => {
const items = cloneDeep(testData)
return () => {
items
.sort((a, b) => b.currDate - a.currDate)
.filter((el) => el.name.includes("ab"))
.map((item) => ({
...item,
someString: item.someString.toUpperCase(),
}))
}
}),
b.add("filter -> sort -> map", () => {
const items = cloneDeep(testData)
return () => {
items
.filter((el) => el.name.includes("ab"))
.sort((a, b) => b.currDate - a.currDate)
.map((item) => ({
...item,
someString: item.someString.toLowerCase(),
}))
}
}),
b.add("reduce -> sort", () => {
const items = cloneDeep(testData)
return () => {
items
.reduce((acc, item) => {
if (item.name.includes("ab")) {
acc.push({
...item,
someString: item.someString.toUpperCase(),
})
}
return acc
}, [])
.sort((a, b) => b.currDate - a.currDate)
}
}),
b.add("for..of -> sort", () => {
const items = cloneDeep(testData)
return () => {
const result = []
for (const item of items) {
if (item.name.includes("ab")) {
result.push({
...item,
someString: item.someString.toUpperCase(),
})
}
}
result.sort((a, b) => b.currDate - a.currDate)
}
}),
b.add("for -> sort", () => {
const items = cloneDeep(testData)
return () => {
const result = []
for (let i = 0; i < items.length; i++) {
if (items[i].name.includes("ab")) {
result.push({
...items[i],
someString: items[i].someString.toUpperCase(),
})
}
}
result.sort((a, b) => b.currDate - a.currDate)
}
}),
b.cycle(),
b.complete(),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment