In these two files if you change getToken{slow,fast}'s passed value (just add a random letter anywhere) you'll see that the fast version is getting type checked about 3x to 5x faster than the slow one.
I'm not sure why using key remapping and using keyof {}
is about 3x to 5x faster when doing type checking.
My guess is that in the slow version is using index access with the {}[keyof Theme]
which is generally slower?
- Slow version: https://tsplay.dev/WJ4bRN
- Fast version: https://tsplay.dev/w24J4m
Today did some actual performance tracing of the two variants:
- slow.ts - took 450ms to do type-checking
- fast.ts - took only 80ms to do type-checking
What's fascinating is that slow.ts is triggering this structuredTypeRelatedTo
which is I think the culprit here.
On parallel with type-checking (structuredTypeRelatedTo) took:
- slow.ts - 1100ms
- fast.ts - 140ms (no structuredTypeRelatedTo)
My guess is that the culprit is the index access signature.
So whats happening is in slow.ts
we are using the index access signature which is triggering the structuredTypeRelatedTo
function which does type checking for index access signatures.
https://github.com/microsoft/TypeScript/blob/main/src/compiler/checker.ts#L19124
And I assume that is the root cause of the slowness, the checker has to validate and typecheck that keyof Theme
(which is a HUGE union) is indexable with the mapped type.
But in the fast.ts
we are not using index access signature thus there is no need to do that extra typechecking, we just need to get all of it's keys. Thus it resolves faster.