Skip to content

Reduce Typescript compilation running time in Bazel unit tests #27426

Closed

Description

@filipesilva

Typescript compilation is not always part of the critical path. When it is, it ranges from ~50ms to 5s. It is likely overshadowed by Angular Template compilation when present. Improving the performance of TseTse can help here, since in Bazel on Angular performance it was shown that TseTse takes around half the total time of even small compilations, and scales poorly

Activity

  1. added this to the needsTriage milestone on Dec 3, 2018
  2. filipesilva commented on Dec 11, 2018

    @filipesilva
    ContributorAuthor

    I took a Bazel profile and Chrome profile of yarn bazel build //packages/compiler at 30a3b49 with a single space change (in a string inside packages/compiler/src/assertions.ts) using bazelbuild/rules_typescript#345. This profile used worker support.

    You can analyze the bazel profile with yarn bazel analyze-profile ngc-with-profiler.bazelprofile. The relevant part is the critical path:

    Critical path (11.696 s):
        Id        Time Percentage   Description
       519    11.696 s  100.00%   action 'Compiling TypeScript (devmode) //packages/compiler compiler'
    

    This means all of the time in the critical path was spent in typescript compilation.

    As a point of comparison, in Bazel on Angular performance we observed around a 14s critical path for //packages/compiler builds. This was without worker support though, and with the node profiler turned on.

    Using the current angular/angular commit, I also tried a couple of builds with a new worker without profiling (~13s), and using an existing worker without profiling (~6s).

    The 12s in our profile are longer than other times for existing workers without profiling, but it's not surprising since profiling itself always makes the process slower.

    To open the Chrome profile I recommend https://github.com/GoogleChromeLabs/ndb, but the performance tab in Chrome works as well.

    The Chrome profile shows a total of 7.9s profiled. It's not unusual to miss a couple of seconds as the profiler starts up, but perhaps the missing time should be further scrutinized since it might be taken up on protobuff processing in the worker process.

    Regardless, the 7.9s is similar enough to previous durations of the critical path with workers and without the profiler (~6s) that it is plausible.

    The call tree of the compilation shows the major contributors to time as;

    • TypeScripts emit at 3.1s
    • TseTse's Checker.execute at 1.9s
    • TypeScripts gatherSemanticDiagnostics at 1.8s

    image

    These values are similar to the ones observed in Bazel on Angular performance.

    rules_typescript keeps worker processes running, but Bazel workers have no affinity for specific builds so they should be roughly similar to just running tsc without watch.

    To obtain a baseline of what would be optimal performance, I also ran a few tsc -p packages/compiler/tsconfig-build.json, which yielded ~8s compilation time.

    Then I also took a profile using node --inspect-brk node_modules/typescript/bin/tsc -p packages/compiler/tsconfig-build.json and uploaded it as bare-tsc-with-profiler.cpuprofile.

    The call tree of the compilation shows the major contributors to time as;

    • emit at 11s
    • createProgram at 1.6s
    • getGlobalDiagnostics at 0.9s

    The 4.1s spent at process.exit should be ignored as an artifact of taking a manual profile, because in those you have to wait for the process to finish and manual disconnect the profiler.

    image

    This baseline is interesting because it actually takes much longer than the rules_typescript compilation at emit and much less time at everything else.

    Thus three questions come to mind:

    • why is emit in rules_typescript much shorter?
    • why are diagnostics in rules_typescript much longer?
    • can time spent in TseTse be reduced?
  3. filipesilva commented on Dec 11, 2018

    @filipesilva
    ContributorAuthor

    We can look further into the "why is emit in rules_typescript much shorter?" question by seeing the differences between the call stack and time spent in it for both rules_typescript compilation and bare tsc compilation:

    rules_typescript compilation

    image

    bare tsc compilation

    image

    Within emit, both spend a long time inside emitSourceFileOrBundle (3.0 vs 5.8s). But bare tsc also spend a long time in a function that is wholly absent in rules_typescript: getEmitResolver. This function seems to be getting diagnostics while emitting.

    It's also interesting that all of bare tsc's function calls are in lib/tsc.js and all of rules_typescript are in lib/typescript.js`. This is likely an artifact of typescripts packaging though, since both these files are very large bundles.

  4. filipesilva commented on Dec 11, 2018

    @filipesilva
    ContributorAuthor

    Inside tsc_wrapped there are switches where both the StrictDeps and TseTse plugins can be disabled.

    To see the impact each one has on the build time, I took 5 build times when using both, none, and each individually. To ensure Bazel truly run the build I again added/removed spaces inside a packages/compiler/src/assertions.ts.

    • Builds with both StrictDeps and TseTse and activated took ~5.89s,
    • Builds with neither took ~3.84s.
    • Builds with only StrictDeps took ~4.87s.
    • Builds with only TseTse took ~5.13s.

    It looks like using both StrictDeps and TseTse takes up roughly 35% (2.05s) of the total compilation time (5.89s).

  5. filipesilva commented on Dec 12, 2018

    @filipesilva
    ContributorAuthor

    @clydin did some work in bazelbuild/rules_typescript#346 that should help reduce time spent in TseTse.

    He also mentioned this:

    for the tsetse rules, check-return-value is probably the major performance issue out of all of them
    also the most complicated
    getText and typeToString should be avoided
    they both do a massive amount of work behind the calls
    i was going to do some research to see if the type flags could be used instead of the later (or at least partially)
    a numerical comparison of the type flags should be much faster
    there’s also a decent amount of unneeded string comparison and manipulation
    the later of which is really bad for the GC since it needs to clean up every intermediate string at some point
    and that rule is being run for almost every call node in the entire program
    also, something to profile is whether the use of the type checker to initially get the return type of the call signature and check if it is void is a net gain (versus not doing that check at all)
    so the first thing it does is check if the return type is void and then bail if it is
    well all the functions it checks for don’t return void
    so if nothing matches farther down it just exits anyway
    so if we optimize the actually checks, that first check may not be needed

  6. filipesilva commented on Dec 17, 2018

    @filipesilva
    ContributorAuthor

    I noticed many calls inside tsc_wrapped were using perfTrace, which is an custom option to trace performance of tsc_wrapped.

    I used it to get only the performance numbers for TseTse and StrictDeps. Below is a small sample, where checkModuleDeps corresponds to StrictDeps, and checkConformance corresponds to TseTse:

    checkModuleDeps 549.301025390625
    checkConformance 10485.899963378906
    checkModuleDeps 198.301025390625
    checkConformance 2598.5
    checkModuleDeps 156.39898681640625
    checkConformance 34632.09899902344
    checkModuleDeps 144.79998779296875
    checkConformance 12827.601013183594
    checkModuleDeps 103.5999755859375
    checkConformance 409.79998779296875
    checkModuleDeps 129
    checkConformance 551.7990112304688
    checkModuleDeps 100.3990478515625
    checkConformance 1857.300048828125
    checkModuleDeps 132.4990234375
    checkConformance 41.9010009765625
    checkModuleDeps 110.39996337890625
    checkConformance 1681.5
    checkModuleDeps 92.5
    checkConformance 1122.8999633789062
    checkModuleDeps 151.70001220703125
    checkConformance 12397.700012207031
    checkModuleDeps 168.29998779296875
    checkConformance 10857.700988769531
    checkModuleDeps 106.5999755859375
    

    checkModuleDeps (and thus StrictDeps) never takes very long, unlike checkConformance (thus TseTse).

    Looking a bit deeper at the structure of the tsc_wrapped pluginApi, I no longer think StrictDeps has any noticeable impact on performance.

    Each plugin is proxying getSemanticDiagnostics, by calling the previous getSemanticDiagnostics and then wrapping it's own code inside a perfTrace.

    The TseTse plugin looks like this:

    export const PLUGIN: pluginApi.Plugin = {
      wrap(program: ts.Program, disabledTsetseRules: string[] = []): ts.Program {
        const checker = new Checker(program);
        registerRules(checker, disabledTsetseRules);
        const proxy = pluginApi.createProxy(program);
        proxy.getSemanticDiagnostics = (sourceFile: ts.SourceFile) => {
          const result = [...program.getSemanticDiagnostics(sourceFile)];
          perfTrace.wrap('checkConformance', () => {
            result.push(...checker.execute(sourceFile)
                            .map(failure => failure.toDiagnostic()));
          });
          return result;
        };
        return proxy;
      },
    };
    

    And the StrictDeps one looks like this:

    export const PLUGIN: pluginApi.Plugin = {
      wrap: (program: ts.Program, config: StrictDepsPluginConfig): ts.Program => {
        const proxy = pluginApi.createProxy(program);
        proxy.getSemanticDiagnostics = function(sourceFile: ts.SourceFile) {
          const result = [...program.getSemanticDiagnostics(sourceFile)];
          perfTrace.wrap('checkModuleDeps', () => {
            result.push(...checkModuleDeps(
                sourceFile, program.getTypeChecker(), config.allowedStrictDeps,
                config.rootDir, config.ignoredFilesPrefixes));
          });
          return result;
        };
        return proxy;
      }
    };
    

    Keep this structure in mind and matching it to the profile, we get the following blocks:
    image

    So it now looks like StrictDeps takes a negligible amount of time and TseTse takes as long as normal TypeScript semantic diagnostics.

  7. filipesilva commented on Dec 17, 2018

    @filipesilva
    ContributorAuthor

    To figure out which of the TseTse rules take most time, I used added direct console logging to perfTrace.wrap and summed up all logs for checkConformance (TseTse):

    • All rules: 2,142ms
    • No rules: 80ms
    • CheckReturnValueRule: 2,102ms
    • EqualsNanRule: 102ms
    • BanExpectTruthyPromiseRule: 92ms
    • MustUsePromisesRule: 1,174ms
    • BanPromiseAsConditionRule: 386 ms

    CheckReturnValueRule and MustUsePromisesRule are by far the rules that take longer.

  8. filipesilva commented on Dec 17, 2018

    @filipesilva
    ContributorAuthor

    In both CheckReturnValueRule and MustUsePromisesRule, the very first instruction is calling the type checker using const signature = checker.typeChecker.getResolvedSignature(node); over all nodes of type ts.SyntaxKind.CallExpression.

    Using the type checker is known to be slow. One avenue to speed these rules up might be to defer any calls to the type checker to as last in the rule as possible, giving an opportunity for other checks to return before hitting the type checker.

  9. filipesilva commented on Dec 17, 2018

    @filipesilva
    ContributorAuthor

    By moving the non-typechecker checks earlier in the process, I was able to observe significant savings in the perfTrace.wrap total times:

    • CheckReturnValueRule: 1,036ms, down from 2,102ms
    • MustUsePromisesRule: 119ms, down from 1,174ms

    PR with changes in bazelbuild/rules_typescript#359

  10. filipesilva commented on Dec 18, 2018

    @filipesilva
    ContributorAuthor

    I ran yarn bazel build //packages/compiler --show_result=0 8 times while changing a string inside packages/compiler/src/assertions.ts, and averaged the last 5 critical path times with and without the changes in bazelbuild/rules_typescript#359:

    • without changes: ~4.92s
    • with changes: ~5.98s

    So about a 18% improvement.

    I think it is possible to get up to half a second less (~9% extra) with a comprehensive refactor of the tsetse rules with the goal of avoiding the type checker further.

    However that would be a fair bit of work, and might be useless once microsoft/TypeScript#28584 is merged.

    So I advise against it, and am closing this issue for now as fixed by bazelbuild/rules_typescript#359.

  11. angular-automatic-lock-bot commented on Sep 14, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  12. locked and limited conversation to collaborators on Sep 14, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions