Skip to content

Commit

Permalink
fix(perf): add cache for fs calls (kulshekhar#908)
Browse files Browse the repository at this point in the history
  • Loading branch information
IOuser committed Jan 8, 2019
1 parent 1235ffe commit ca09996
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions src/compiler.ts
Expand Up @@ -131,6 +131,7 @@ export function createCompiler(configs: ConfigSet): TsCompiler {
...serviceHostDebugCtx,
[LogContexts.logLevel]: LogLevels.trace,
}

const serviceHost = {
getScriptFileNames: () => Object.keys(memoryCache.versions),
getScriptVersion: (fileName: string) => {
Expand All @@ -157,11 +158,11 @@ export function createCompiler(configs: ConfigSet): TsCompiler {
}
return ts.ScriptSnapshot.fromString(contents)
},
fileExists: ts.sys.fileExists,
readFile: logger.wrap(serviceHostTraceCtx, 'readFile', ts.sys.readFile),
readDirectory: ts.sys.readDirectory,
getDirectories: ts.sys.getDirectories,
directoryExists: ts.sys.directoryExists,
fileExists: memoize(ts.sys.fileExists),
readFile: logger.wrap(serviceHostTraceCtx, 'readFile', memoize(ts.sys.readFile)),
readDirectory: memoize(ts.sys.readDirectory),
getDirectories: memoize(ts.sys.getDirectories),
directoryExists: memoize(ts.sys.directoryExists),
getNewLine: () => '\n',
getCurrentDirectory: () => cwd,
getCompilationSettings: () => compilerOptions,
Expand Down Expand Up @@ -224,6 +225,22 @@ export function createCompiler(configs: ConfigSet): TsCompiler {
return { cwd, compile, getTypeInfo, extensions, cachedir, ts }
}

type AnyFn = (...args: any[]) => any
function memoize<T extends AnyFn = AnyFn>(fn: T): T {
const cache = new Map()

return ((arg: string) => {
const entry = cache.get(arg)
if (entry !== undefined) {
return entry
}

const res = fn(arg)
cache.set(arg, res)
return res
}) as T
}

/**
* Internal source output.
*/
Expand Down

0 comments on commit ca09996

Please sign in to comment.