Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(perf): add cache for fs calls when using language service (#908) #940

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 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,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