From 0b45a12b7f9d728057731295bc7559f1690ca2ff Mon Sep 17 00:00:00 2001 From: kuroljov Date: Wed, 5 Jul 2017 15:06:03 +0300 Subject: [PATCH] module: addBuiltinLibsToObject refactoring Replace forEach-loop by for-loop for several reasons. One of them being performance. Loop over a small array is fast anyway, but this will make code more consistent across the project. Feels like Node.js is trying to be as fast as possible. Move "setReal" function definition out of the loop and make it bindable. Defining a function inside loop is considered bad practice in general. Predefine configurable and enumerable as these are staying consistent across the function. --- lib/internal/module.js | 51 ++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/lib/internal/module.js b/lib/internal/module.js index 08d8f770c8d873..016a3437642cbe 100644 --- a/lib/internal/module.js +++ b/lib/internal/module.js @@ -83,43 +83,50 @@ const builtinLibs = [ 'string_decoder', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'zlib' ]; +// Make built-in modules available directly (loaded lazily). function addBuiltinLibsToObject(object) { - // Make built-in modules available directly (loaded lazily). - builtinLibs.forEach((name) => { + const configurable = true; + const enumerable = false; + + // Setter function that will be bound to some lib name + function setReal(libname, value) { + // Deleting the property before re-assigning it disables the + // getter/setter mechanism. + delete object[libname]; + object[libname] = value; + } + + for (var n = 0, len = builtinLibs.length; n < len; n++) { // Goals of this mechanism are: // - Lazy loading of built-in modules // - Having all built-in modules available as non-enumerable properties // - Allowing the user to re-assign these variables as if there were no // pre-existing globals with the same name. + const libname = builtinLibs[n]; + const set = setReal.bind(null, libname); - const setReal = (val) => { - // Deleting the property before re-assigning it disables the - // getter/setter mechanism. - delete object[name]; - object[name] = val; - }; - - Object.defineProperty(object, name, { + Object.defineProperty(object, libname, { get: () => { - const lib = require(name); + const lib = require(libname); - // Disable the current getter/setter and set up a new - // non-enumerable property. - delete object[name]; - Object.defineProperty(object, name, { + // Disable the current getter/setter + delete object[libname]; + + // Set up a new non-emumerable propery + Object.defineProperty(object, libname, { get: () => lib, - set: setReal, - configurable: true, - enumerable: false + set, + configurable, + enumerable }); return lib; }, - set: setReal, - configurable: true, - enumerable: false + set, + configurable, + enumerable }); - }); + } } module.exports = exports = {