-
Notifications
You must be signed in to change notification settings - Fork 88
Equality via pattern-matching compiles to slow code #3914
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I agree that we should try and optimize such patterns for equality function. That being said, and while waiting for the necessary optimizations to be implemented, here is a pattern that works just as well (if not better, since it also gives you a comparison function), and that happens to be correctly optimized: type t =
| A
| B
| C
| D
| E
| F
(* the badly-optimized code *)
let equal_unoptimized t t' =
match t, t' with
| A, A
| B, B
| C, C
| D, D
| E, E
| F, F -> true
| _ -> false
(* let's define an auxiliary function that returns a "discriminant" that
distinguishes the various constructors. *)
let discr = function
| A -> 0
| B -> 1
| C -> 2
| D -> 3
| E -> 4
| F -> 5
let compare t t' =
(discr t) - (discr t')
let equal_optimized t t' = compare t t' = 0
(* an even better one, though we should try and optimize things so that it's not that different from the one before *)
let equal_best t t' = (discr t) = (discr t') That being said, this pattern is currently quite fragile and only works really well if the
@bclement-ocp I wonder (or rather do not recall) if your upcoming work on the typing env and match-in-match related heuristics would actually see that the affine relation in these switches ? |
In the current plan we'll see an array, but it shouldn't be too hard to convert to an affine relation (in fact we could do this in |
Uh oh!
There was an error while loading. Please reload this page.
example:
leads to
The text was updated successfully, but these errors were encountered: