Last active
January 29, 2025 13:54
-
-
Save artalar/2879bb48cb18059a6f47a094936d4bd9 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
import { performance } from 'node:perf_hooks' | |
const measure = (name: string, cb: () => void) => { | |
const start = performance.now() | |
cb() | |
console.log(name, performance.now() - start) | |
} | |
class LLNode { | |
value = 0 | |
constructor(public next?: LLNode) {} | |
inc() { | |
this.value += 1 | |
} | |
} | |
const test = (reverse = false) => { | |
let head = new LLNode() | |
let i = 1000 | |
while (--i) head = new LLNode(head) | |
let list: Array<LLNode> | |
measure('allocate list', () => { | |
list = [] | |
let next: undefined | LLNode = head | |
while (next) { | |
list.push(next) | |
next = next.next | |
} | |
}) | |
const tests = [ | |
() => | |
measure('walk on list', () => { | |
// console.log('list.length', list.length) | |
for (let i = 0; i < list.length; i++) { | |
list[i]!.inc() | |
} | |
}), | |
() => | |
measure('walk on sibling', () => { | |
let next: undefined | LLNode = head | |
while (next) { | |
next.inc() | |
next = next.next | |
} | |
}), | |
] | |
if (reverse) tests.reverse() | |
tests.forEach((cb) => cb()) | |
console.log( | |
'sum', | |
list!.reduce((acc, { value }) => acc + value, 0), | |
) | |
} | |
test() | |
test(true) | |
test() | |
test(true) |
Author
artalar
commented
Jan 29, 2025
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment