Replies: 1 comment
-
Hey, thanks for creating this benchmark! I thought this might be a little bit skewed given the simplicity of the input and the fact that the original version of the code was likely to be JIT compiled away by v8, so I went ahead and created benchmarks with random inputs. Here is my pull request: bdbaraban/ts-pattern-benchmark#1 The difference in terms of performance is less dramatic in this case, but TS-Pattern is still around 10-30 times slower than inlined runtime checks. That said, I think it's ok given the DX improvement. TS-Pattern: const testTSPattern = (input: unknown) => {
return match(input)
.with({ type: 'a', value: { x: P.number, y: P.number } }, () => '1')
.with({ type: 'b', value: [1, ...P.array(P.number)] }, () => '2')
.with({ type: 'c', name: P.string, age: P.number }, () => '3')
.otherwise(() => '4');
}; Native: const testIfElse = (input: unknown) => {
if (
input &&
typeof input === 'object' &&
'type' in input &&
input.type === 'a' &&
'value' in input &&
input.value &&
typeof input.value === 'object' &&
'x' in input.value &&
typeof input.value.x === 'number' &&
'y' in input.value &&
typeof input.value.y === 'number'
) {
return '1';
} else if (
input &&
typeof input === 'object' &&
'type' in input &&
input.type === 'b' &&
'value' in input &&
Array.isArray(input.value) &&
input.value[0] === 1 &&
input.value.slice(1).every((x) => typeof x === 'number')
) {
return '2';
} else if (
input &&
typeof input === 'object' &&
'type' in input &&
input.type === 'c' &&
'name' in input &&
typeof input.name === 'string' &&
'age' in input &&
typeof input.age === 'number'
) {
return '3';
} else {
return '4';
}
}; Checkout the PR description for full benchmark results. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello! I wanted to share benchmarks I've recently generated comparing ts-pattern to built-in conditional execution flows, specifically,
if/else
branches,switch
statements, and ternaries.Comparing results of matching a single-digit integer input (ten possible cases), I'm finding that
match
statements execute ~100% more slowly than built-in conditional execution flows.https://github.com/bdbaraban/ts-pattern-benchmark
Obviously I do not expect ts-pattern to perform better than JS built-ins; however, it may be helpful to reference runtime benchmarks in the README for developer transparency.
Beta Was this translation helpful? Give feedback.
All reactions