Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Add beam_ssa_opt pass to streamline comparisons #10264

@josevalim

Description

@josevalim

Is your feature request related to a problem? Please describe.

In Erlang/Elixir, there are several data structures that rely on order, such as gb_trees, ordsets, and Elixir’s upcoming data structure for the type system. Today, those data structures rely on comparisons:

insert_1(Key, Value, {Key1, V, Smaller, Bigger}, S) when Key < Key1 -> 
  ...
insert_1(Key, Value, {Key1, V, Smaller, Bigger}, S) when Key > Key1 -> 
  ...
insert_1(Key, Value, nil, _S) ->
  ...

The issue is that if you have a nested data structure where the difference between the keys are on the leaves, you are doing a lot of repeated work across those three branches (especially if they are equal).

Describe the solution you'd like

@jhogberg suggested this could be done as a pass in the compiler that uses erts_cmp directly, doing the comparison once. Worth noting that the above is only one possibility to write the above. Another option could be:

insert_1(Key, Value, {Key1, V, Smaller, Bigger}, S) when Key == Key1 -> 
  ...
insert_1(Key, Value, {Key1, V, Smaller, Bigger}, S) when Key < Key1 -> 
  ...
insert_1(Key, Value, nil, _S)  ->
  ...

Or even with three comparisons.

Describe alternatives you've considered

Another alternative is to introduce erlang:compare/2 but if it can be done automatically trivially, then that would be fantastic, as it would make all software automatically faster.

Additional context

First proposed here: https://erlangforums.com/t/optimize-erlang-comparisons-or-expose-erlang-compare-2/5110

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions