Reason is faster than JavaScript when using BuckleScript.
The way that you design APIs are different, JavaScript code and the lack of a type system leads to APIs being designed strictly for humans.
In JavaScript is quite common to use strings to identify types and branch
based on it, but comparing strings is quite slow in fact it is O(n)
in
case where both strings have the same length, like tomato
and orange
.
type Fruit = { type: 'tomato' } | { type: 'orange' } | { type: 'grape' }
const fruitColor = (fruit: Fruit) => {
switch (fruit.type) {
case 'tomato': return 'red'
case 'orange': return 'orange'
case 'grape': return 'purple'
}
}
On reason we use variants to solve that problem, but the trick is how variants are encoded in the bucklescript, as you can see below, it uses simple integers that already makes it a lot simpler to compare and validate, without loosing any readability.
// Input
type fruits = | Tomato | Orange | Grape
let fruit_color = fun
| Tomato => "red"
| Orange => "orange"
| Grape => "purple"
// Output
function fruit_color(param) {
switch (param) {
case /* Tomato */0 : return "red";
case /* Orange */1 : return "orange";
case /* Grape */2 : return "purple";
}
}