Last active
April 30, 2023 20:34
-
-
Save Kruithne/1093fc49678df1feb6a6b2c7df3d9f02 to your computer and use it in GitHub Desktop.
Primitive array benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let arr; | |
let foo = {}; | |
// Category A: Pre-determined array size with index assignment | |
console.log("Pre-determined array size with index assignment"); | |
console.log("%cSize | Time (ms)", "font-weight: bold"); | |
for (let x of [1000, 1001, 10000, 10001, 100000, 100001, 10_000_000, 10_000_001]) { | |
const iterations = 10; // number of times to run the test | |
const start = performance.now(); | |
for (let i = 0; i < iterations; i++) { | |
arr = Array(x); | |
for (let j = 0; j < x; j++) { | |
arr[j] = Object.assign({}, foo); | |
} | |
} | |
const end = performance.now(); | |
console.log(`%c${x} | ${(end - start) / iterations}`, "color: blue"); | |
} | |
// Category B: Non-determined array size with index assignment | |
console.log("\nNon-determined array size with index assignment"); | |
console.log("%cSize | Time (ms)", "font-weight: bold"); | |
for (let x of [1000, 1001, 10000, 10001, 100000, 100001, 10_000_000, 10_000_001]) { | |
const iterations = 10; // number of times to run the test | |
const start = performance.now(); | |
for (let i = 0; i < iterations; i++) { | |
arr = []; | |
for (let j = 0; j < x; j++) { | |
arr[j] = Object.assign({}, foo); | |
} | |
} | |
const end = performance.now(); | |
console.log(`%c${x} | ${(end - start) / iterations}`, "color: green"); | |
} | |
// Category C: Non-determined array size with .push() | |
console.log("\nNon-determined array size with .push()"); | |
console.log("%cSize | Time (ms)", "font-weight: bold"); | |
for (let x of [1000, 1001, 10000, 10001, 100000, 100001, 10_000_000, 10_000_001]) { | |
const iterations = 10; // number of times to run the test | |
const start = performance.now(); | |
for (let i = 0; i < iterations; i++) { | |
arr = []; | |
for (let j = 0; j < x; j++) { | |
arr.push(Object.assign({}, foo)); | |
} | |
} | |
const end = performance.now(); | |
console.log(`%c${x} | ${(end - start) / iterations}`, "color: red"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment