Last active
March 10, 2021 11:46
-
-
Save Domiii/562d521bd738f2c00509381029431b7f to your computer and use it in GitHub Desktop.
This code sample is used to explain how to find memory leaks in Node.js in this post: https://stackoverflow.com/questions/66473378/memory-leaks-in-node-js-how-to-analyze-allocation-tree-roots
This file contains hidden or 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
// ########################################################################### | |
// util | |
// ########################################################################### | |
const N = 100e6; | |
// async function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } | |
/** | |
* | |
* @param {number} N number of bytes | |
* @param {[]} a the array to add pressure to | |
*/ | |
function addPressure(a) { | |
console.log('adding pressure', N) | |
// NOTE: padStart does not allow that big a number, so we have to run it multiple times. | |
const S = 100e6; | |
const I = Math.ceil(N / S); | |
for (let i = 0; i < I; ++i) { | |
const s = ''.padStart(S, 'l') + 'x'; | |
a.push(s); | |
// NOTE: random access into the string actually allocates it | |
// console.log( | |
a.map(s => s[S / 2] + s.length).join(', ') | |
// ); | |
} | |
} | |
function gc() { | |
global.gc(); | |
console.log('gc'); | |
} | |
// ########################################################################### | |
// run test | |
// ########################################################################### | |
let a; | |
function test1() { | |
const b = []; | |
addPressure(b); | |
a = b; | |
gc(); | |
} | |
test1(); | |
debugger; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment