Created
March 20, 2025 20:06
-
-
Save tmikov/6d19b6387800f0e0cf29fdf71797691e to your computer and use it in GitHub Desktop.
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
if (typeof console === "undefined") | |
console = {log: print} | |
function benchmark(iterations, pr) { | |
const obj = { value: 42 }; | |
const proxy = new Proxy(obj, { | |
get(target, prop) { | |
return prop === "value" ? 42 : undefined; | |
} | |
}); | |
if (pr) | |
console.log(`Benchmarking with ${iterations} iterations...`); | |
// Plain object access | |
let start = Date.now(); | |
let sum1 = 0; | |
for (let i = 0; i < iterations; i++) { | |
sum1 += obj.value; | |
} | |
let end = Date.now(); | |
let timeObj = end - start; | |
// Proxy access | |
start = Date.now(); | |
let sum2 = 0; | |
for (let i = 0; i < iterations; i++) { | |
sum2 += proxy.value; | |
} | |
end = Date.now(); | |
let timeProxy = end - start; | |
if (pr) { | |
console.log(`Plain object: ${timeObj} ms total, ${iterations} iterations, ${(timeObj / iterations).toFixed(6)} ms/iteration`); | |
console.log(`Proxy: ${timeProxy} ms total, ${iterations} iterations, ${(timeProxy / iterations).toFixed(6)} ms/iteration`); | |
} | |
} | |
benchmark(10_000_000, false); | |
benchmark(10_000_000, true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment