sharkdp / numbat

A statically typed programming language for scientific computations with first class support for physical dimensions and units
https://numbat.dev
Apache License 2.0
1.16k stars 50 forks source link

Avoid cloning the typechecker in `elaborate_statement` #543

Closed GuerricChupin closed 1 month ago

GuerricChupin commented 1 month ago

Running numbat with cargo flamegraph, I found that a significant portion of the startup time was spent in the DefineFunction branch of elaborate_statement in the typechecker just cloning TypeChecker (line 1313 of numbat/src/typechecker/mod.rs). I think this is only due to the need to save and restore the environment, value_namespace and type_namespace members of TypeChecker after we have finished checking the function definition to remove any local names before continuing.

To avoid this, I experimented with replacing the HashMaps in Environment and NameSpace with a stack of HashMaps (a MapStack for lack of a better name) that can be used to save the current state of the map (when we start checking a definition) and restore it (when we are done) but otherwise behaves like a hash map. This seems to give good results to reduce startup time with little impact on the typechecker's code itself. Running numbat on the files in the example/ directory with hyperfine, I observe a ~20-25% reduction in time. I've attached the results as Markdown files for master and this branch as well as the output of cargo flamegraph for master.

bench-master.md bench-avoid-cloning-the-typechecker.md

flamegraph.svg