Skip to content

Instantly share code, notes, and snippets.

@ryuheechul
Created March 15, 2023 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryuheechul/8f53e92b180b59f70f0674745fd20a0b to your computer and use it in GitHub Desktop.
Save ryuheechul/8f53e92b180b59f70f0674745fd20a0b to your computer and use it in GitHub Desktop.
Simple javascript memory leak tester
// a quick memory leak tester
// TODO: actually verify and make it objectively testable
function getRandomInt(max: number) {
return Math.floor(Math.random() * max);
}
const size = 2000 * 1000 as const; // whatever length to make the size big enough at each step
function malloc() {
const arrInHeap = [...Array(size).keys()];
return arrInHeap;
}
function randomCalc(arr: number[]) {
// use randomness to prevent runtime/compiler to optimize which prevent the whole purpose of creating a big memory actually allocated
const a = arr[getRandomInt(size)];
const b = arr[getRandomInt(size)];
return a + b;
}
// insert this into where the subject object that you think it might not release when its no longer referenced
const m = malloc();
// insert these where the representation object's aliveness
const r = randomCalc(m); console.log(r);
const example = () => {
const m = malloc();
return () => {
const r = randomCalc(m); console.log(r);
}
}
const exampleNoLeak = example();
const aliveness = exampleNoLeak;
aliveness();
aliveness();
aliveness();
aliveness();
// should be released after this point - but strictly this is up to the runtime so might see the release only later;
const exampleLeak1 = example();
const exampleLeak2 = example();
exampleLeak2.arbitraryRef = exampleLeak1;
exampleLeak1.arbitraryRef = exampleLeak2;
exampleLeak2(); exampleLeak1();
exampleLeak2(); exampleLeak1();
exampleLeak2(); exampleLeak1();
exampleLeak2(); exampleLeak1();
// will be leaks even after here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment