From 909dd9561a40daea507dfe5155c31c273918e2b5 Mon Sep 17 00:00:00 2001 From: xiaoc Date: Sat, 25 Oct 2014 13:08:14 +0800 Subject: [PATCH 1/2] add cache for module with same version In a large project developed with node.Js, some modulex are used frequently, let's say ```underscore``` or ```lodash```, module A is depended on it,and module B is depended on it too, and they are depended on the same version. So module ```underscore``` is loaded twice , right? and that may cost more memory, so why don't we set the cache for the same module with the same version. Thanks! --- lib/module.js | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/module.js b/lib/module.js index 564f6c49d6cb..c70602321560 100644 --- a/lib/module.js +++ b/lib/module.js @@ -25,7 +25,7 @@ var runInThisContext = require('vm').runInThisContext; var runInNewContext = require('vm').runInNewContext; var assert = require('assert').ok; var fs = NativeModule.require('fs'); - +var moduleVersionCache = {}, // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. @@ -104,7 +104,7 @@ function readPackage(requestPath) { } try { - var pkg = packageMainCache[requestPath] = JSON.parse(json).main; + var pkg = packageMainCache[requestPath] = JSON.parse(json); } catch (e) { e.path = jsonPath; e.message = 'Error parsing ' + jsonPath + ': ' + e.message; @@ -116,9 +116,24 @@ function readPackage(requestPath) { function tryPackage(requestPath, exts) { var pkg = readPackage(requestPath); - if (!pkg) return false; + if (!(pkg && pkg.main)) return false; + + var name = pkg.name, + version = pkg.version, + main = pkg.main; + + var cache = moduleVersionCache[name]; + if(!cache){ + cache = moduleVersionCache[name] = {}; + } + + var filename = cache[version]; + + if(!filename) { + filename = path.resolve(requestPath, main); + cache[version] = filename; + } - var filename = path.resolve(requestPath, pkg); return tryFile(filename) || tryExtensions(filename, exts) || tryExtensions(path.resolve(filename, 'index'), exts); } From 167aedca9989b3bd051a70f9f95f3f16b7273ad8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B7=98=E5=B0=8F=E6=9D=B0?= Date: Sat, 25 Oct 2014 16:21:10 +0800 Subject: [PATCH 2/2] sorry, stupid mistake --- lib/module.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/module.js b/lib/module.js index c70602321560..a2f70ca380ca 100644 --- a/lib/module.js +++ b/lib/module.js @@ -25,7 +25,7 @@ var runInThisContext = require('vm').runInThisContext; var runInNewContext = require('vm').runInNewContext; var assert = require('assert').ok; var fs = NativeModule.require('fs'); -var moduleVersionCache = {}, +var moduleVersionCache = {}; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break.