Skip to content

Instantly share code, notes, and snippets.

@aquapi
Created March 16, 2025 14:03
Show Gist options
  • Save aquapi/12a1e090eee89bf252abf88743054386 to your computer and use it in GitHub Desktop.
Save aquapi/12a1e090eee89bf252abf88743054386 to your computer and use it in GitHub Desktop.
// Dependencies: ts-pattern, mitata
import { match, P } from 'ts-pattern';
import { summary, run, bench, type k_state, do_not_optimize } from 'mitata';
summary(() => {
type Data =
| { type: 'text'; content: string }
| { type: 'img'; src: string };
type Result =
| { type: 'ok'; data: Data }
| { type: 'error'; error: Error };
const tsPat = (res: Result) => match(res)
.with({ type: 'error' }, () => 'oops')
.with({ type: 'ok', data: { type: 'text' } }, (res) => res.data.content)
.with({ type: 'ok', data: { type: 'img', src: P.select() } }, (src) => src)
.exhaustive();
const switchFn = (res: Result) => {
switch (res.type) {
case 'ok':
return res.data.type === 'text'
? res.data.content
: res.data.src
case 'error':
return 'oops';
}
}
const generate = (_: any, i: number): Result => {
switch (i % 3 as 0 | 1 | 2) {
case 0:
return { type: 'error', error: new Error('what') };
case 1:
return { type: 'ok', data: { type: 'text', content: `ID: ${Math.random()}` } };
case 2:
return { type: 'ok', data: { type: 'img', src: 'https://example.com' } };
}
}
bench('ts-pattern', function* (state: k_state) {
const arr = new Array(state.get('size')).fill(null);
yield {
[0]() {
return arr.map(generate);
},
bench(arr: Result[]) {
do_not_optimize(arr.map(tsPat));
}
};
}).range('size', 1, 2 ** 10, 2);
bench('switch', function* (state: k_state) {
const arr = new Array(state.get('size')).fill(null);
yield {
[0]() {
return arr.map(generate);
},
bench(arr: Result[]) {
do_not_optimize(arr.map(switchFn));
}
};
}).range('size', 1, 2 ** 10, 2);
});
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment