From f29c3a083642d9cc079864dfc78d6f961a600f52 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 18 Jan 2013 08:50:07 -0800 Subject: [PATCH] Check if module path is already loaded before doing fs operations resolve now checks the existence of a module already loaded at the given path before checking if the file exists on disk. This removes the need for many redundant fs.exists and fs.isFile calls for already loaded modules. This speeds up package loading since most packages have a common set of requires that were doing needless fs operations for each searched path when the module was already in the cache at that path. --- src/stdlib/require.coffee | 46 ++++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 13 deletions(-) diff --git a/src/stdlib/require.coffee b/src/stdlib/require.coffee index 5504ee78b..94e7f1b65 100644 --- a/src/stdlib/require.coffee +++ b/src/stdlib/require.coffee @@ -73,16 +73,25 @@ resolve = (name, {verifyExistence}={}) -> file = file.replace '../', "#{prefix}/" if file[0] isnt '/' - paths.some (path) -> - fileExists = /\.(.+)$/.test(file) and __exists "#{path}/#{file}" - jsFileExists = not /\.(.+)$/.test(file) and __exists "#{path}/#{file}.js" - - if jsFileExists - file = "#{path}/#{file}.js" - else if fileExists + moduleAlreadyLoaded = paths.some (path) -> + if __moduleExists "#{path}/#{file}" file = "#{path}/#{file}" - else if expanded = __expand "#{path}/#{file}" + else if __moduleExists "#{path}/#{file}.js" + file = "#{path}/#{file}.js" + else if expanded = __moduleExpand "#{path}/#{file}" file = expanded + + if not moduleAlreadyLoaded + paths.some (path) -> + fileExists = /\.(.+)$/.test(file) and __exists "#{path}/#{file}" + jsFileExists = not /\.(.+)$/.test(file) and __exists "#{path}/#{file}.js" + + if jsFileExists + file = "#{path}/#{file}.js" + else if fileExists + file = "#{path}/#{file}" + else if expanded = __expand "#{path}/#{file}" + file = expanded else file = __expand(file) or file @@ -92,16 +101,27 @@ resolve = (name, {verifyExistence}={}) -> console.warn("Failed to resolve '#{name}'") if verifyExistence null +__moduleExists = (path) -> + __modules[path] isnt undefined + +__moduleExpand = (path) -> + return path if __moduleExists path + for ext, handler of exts + return "#{path}.#{ext}" if __moduleExists "#{path}.#{ext}" + return "#{path}/index.#{ext}" if __moduleExists "#{path}/index.#{ext}" + null + __expand = (path) -> + modulePath = __moduleExpand path + return modulePath if modulePath + return path if __isFile path for ext, handler of exts - if __exists "#{path}.#{ext}" - return "#{path}.#{ext}" - else if __exists "#{path}/index.#{ext}" - return "#{path}/index.#{ext}" + return "#{path}.#{ext}" if __exists "#{path}.#{ext}" + return "#{path}/index.#{ext}" if __exists "#{path}/index.#{ext}" return path if __exists path - return null + null __exists = (path) -> $native.exists path