Skip to content

Instantly share code, notes, and snippets.

@adammockor
Last active March 14, 2018 07:37
Show Gist options
  • Save adammockor/fbc2919e3fa4f4ba7ae62b09cda4e08f to your computer and use it in GitHub Desktop.
Save adammockor/fbc2919e3fa4f4ba7ae62b09cda4e08f to your computer and use it in GitHub Desktop.
Memory leak test of require-uncached

Run:

  • node memory-leak.js
  • node node fixed-memory-leak.js

Output will be four heapdumps files with coresponding names. Heapdumps can be inspected via Chrome Devtools.

const heapdump = require('heapdump');
const uncached = require('./require-uncached-patch.js');
let i;
for (i = 0; i < 100000; i++) {
require('./module.js')();
}
heapdump.writeSnapshot('./FixedMemoryLeakBefore-' + Date.now() + '.heapsnapshot');
for (i=0; i < 100000; i++) {
uncached('./module.js')();
}
heapdump.writeSnapshot('./FixedMemoryLeakAfter-' + Date.now() + '.heapsnapshot');
const heapdump = require('heapdump');
const uncached = require('require-uncached');
let i;
for (i = 0; i < 100000; i++) {
require('./module.js')();
}
heapdump.writeSnapshot('./MemoryLeakBefore-' + Date.now() + '.heapsnapshot');
for (i=0; i < 100000; i++) {
uncached('./module.js')();
}
heapdump.writeSnapshot('./MemoryLeakAfter-' + Date.now() + '.heapsnapshot');
module.exports = () => {};
{
"name": "require-leak",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"heapdump": "~0.3.7",
"require-uncached": "~1.0.2"
}
}
'use strict';
var path = require('path');
var resolveFrom = require('resolve-from');
var callerPath = require('caller-path');
module.exports = function (moduleId) {
if (typeof moduleId !== 'string') {
throw new TypeError('Expected a string');
}
var filePath = resolveFrom(path.dirname(callerPath()), moduleId);
// delete itself from module parent
if (require.cache[filePath] && require.cache[filePath].parent) {
var i = require.cache[filePath].parent.children.length;
while (i--) {
if (require.cache[filePath].parent.children[i].id === filePath) {
require.cache[filePath].parent.children.splice(i, 1);
}
}
}
// delete module from cache
delete require.cache[filePath];
// return fresh module
return require(filePath);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment