How pattycake optimizes ts-pattern
mainPattycake is a zero-runtime optimizing compiler for ts-pattern. It takes expressive match() expressions and compiles them into optimized chains of if statements. This eliminates the runtime overhead of ts-pattern, typically resulting in a 10-12x performance improvement.
Key Optimizations
- If-statement chains: Converts complex pattern matching logic into direct conditional checks.
- Inlining handlers: When possible,
pattycakeinlines small anonymous or arrow function handlers directly into the generated code to avoid function call overhead and reduce the creation of function objects at runtime. - IIFEs: Uses code blocks (similar to IIFEs) to maintain semantics while optimizing execution flow.
Fallback Behavior
If pattycake encounters a match() expression that it cannot currently optimize (due to unsupported ts-pattern features), it will automatically fallback to using the standard ts-pattern runtime.
// Original ts-pattern code
let html = match(result)
.with(
{ type: 'error', error: { foo: [1, 2] }, nice: '' },
() => '<p>Oups! An error occured</p>',
)
.with({ type: 'ok', data: { type: 'text' } }, function (data) {
return '<p>420</p>';
})
.with(
{ type: 'ok', data: { type: 'img', src: 'hi' } },
(src) => `<img src=${src} />`,
)
.otherwise(() => 'idk bro');
// pattycake compiles this into an optimized if/else chain with direct property checks