Skip to content

Commit

Permalink
fix(perf): add cache for fs calls (#908)
Browse files Browse the repository at this point in the history
  • Loading branch information
IOuser authored and topaxi committed Sep 9, 2019
1 parent 1e40cb1 commit 3dada81
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/compiler.ts
Original file line number Diff line number Diff line change
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,12 +158,12 @@ 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,
realpath: ts.sys.realpath,
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),
realpath: memoize(ts.sys.realpath!),
getNewLine: () => '\n',
getCurrentDirectory: () => cwd,
getCompilationSettings: () => compilerOptions,
Expand Down Expand Up @@ -225,6 +226,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 3dada81

Please sign in to comment.