Last active
December 26, 2018 02:17
-
-
Save evanlucas/973014c1ce218517d4978f9122ac3197 to your computer and use it in GitHub Desktop.
See your most expensive requires
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
'use strict' | |
const Module = require('module') | |
const original = Module.prototype.require | |
const items = new Map() | |
function sorter(a, b) { | |
if (a < b) return -1 | |
if (a > b) return 1 | |
return 0 | |
} | |
function addItem(ms, name) { | |
const item = items.get(ms) || new Set() | |
item.add(name) | |
items.set(ms, item) | |
} | |
Module.prototype.require = function(id) { | |
const parent = this.parent | |
const n = ` -> ${this.id}` | |
const parentName = getParent(parent) | |
const name = `require "${id}" from \n${n}\n${parentName}` | |
const start = process.hrtime() | |
const result = original.call(this, id) | |
const duration = process.hrtime(start) | |
const ms = duration[0] * 1000 + duration[1] / 1e6 | |
addItem(ms, name) | |
return result | |
} | |
setImmediate(() => { | |
const sortedKeys = Array.from(items.keys()).sort(sorter) | |
for (const key of sortedKeys) { | |
for (const item of items.get(key)) { | |
console.log('%sms \n', key, item) | |
} | |
} | |
}) | |
function getParent(parent) { | |
if (parent) { | |
let idx = 1 | |
const buf = [] | |
while (idx++) { | |
buf.push(` -> ${parent.id}`) | |
parent = parent.parent | |
if (!parent) return buf.join('\n') | |
if (idx > 10) break | |
} | |
return buf.join('\n') | |
} | |
return ' -> [none]' | |
} |
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
node -r ./require.js <entrypoint> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment