Created
March 31, 2018 10:25
-
-
Save Hamzali/945f00ffcc82c2850ffb1a659f7e8b7a to your computer and use it in GitHub Desktop.
Anonymous function vs Object reference Performance
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
const NS_PER_SEC = 1e9; | |
const elapsedTimeMs = diff => (((diff[0] * NS_PER_SEC) + diff[1]) / 1e6); | |
const testCount = 1000; | |
const calcResults = (t, heapMem) => console.log("Average Elapsed Time:", (total / testCount).toFixed(2), "ms", "\nHeap Used Memory:", (heapMem / 1e6).toFixed(2), "MB"); | |
let mem = process.memoryUsage(); | |
// anon function :( | |
const obj = {}; | |
console.log("ANON FUNCTIONS: "); | |
let total = 0; | |
let j = 0; | |
while(j < testCount) { | |
let i = 10000; | |
const timeStart = process.hrtime(); | |
while(i--) { | |
obj.method = () => "helloo"; | |
} | |
total += elapsedTimeMs(process.hrtime(timeStart)); | |
j++; | |
} | |
mem = process.memoryUsage().heapUsed - mem.heapUsed; | |
calcResults(total, mem); | |
// object and ref | |
function methodTest() { | |
return "hello"; | |
} | |
const obj2 = {}; | |
console.log("FUNCTION REF AND OBJECT: "); | |
total = 0; | |
j = 0; | |
while(j < testCount) { | |
let i = 10000; | |
const timeStart = process.hrtime(); | |
while(i--) { | |
obj2.method = {m: methodTest, p: ["hell", "yeah"]}; | |
} | |
total += elapsedTimeMs(process.hrtime(timeStart)); | |
j++; | |
} | |
calcResults(total, process.memoryUsage().heapUsed - mem); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment