Add docs and tests for switch.

This commit is contained in:
Stephen Chung
2020-11-14 09:38:16 +08:00
parent b0c66eb5e5
commit 83c7c101d1
5 changed files with 155 additions and 14 deletions

View File

@@ -71,20 +71,25 @@ switch map {
}
```
Switching on [arrays] is very useful when working with Rust enums (see [this chapter]({{rootUrl}}/patterns/enums.md)
for more details).
Difference From If-Else Chain
-----------------------------
Although a `switch` expression looks _almost_ the same as an `if`-`else` chain,
Difference From `if` - `else if` Chain
-------------------------------------
Although a `switch` expression looks _almost_ the same as an `if`-`else if` chain,
there are subtle differences between the two.
### Look-up Table vs `x == y`
A `switch` expression matches through _hashing_ via a look-up table.
Therefore, matching is very fast. Walking down an `if`-`else` chain
will be _much_ slower.
Therefore, matching is very fast. Walking down an `if`-`else if` chain
is _much_ slower.
On the other hand, operators can be [overloaded][operator overloading] in Rhai,
meaning that it is possible to override the `==` operator for integers such
that `if x == y` returns a different result from the built-in default.
that `x == y` returns a different result from the built-in default.
`switch` expressions do _not_ use the `==` operator for comparison;
instead, they _hash_ the data values and jump directly to the correct
@@ -95,3 +100,12 @@ the `==` operator will have no effect.
Therefore, in environments where it is desirable to [overload][operator overloading]
the `==` operator - though it is difficult to think of valid scenarios where you'd want
`1 == 1` to return something other than `true` - avoid using the `switch` expression.
### Efficiency
Because the `switch` expression works through a look-up table, it is very efficient
even for _large_ number of cases; in fact, switching is an O(1) operation regardless
of the size of the data and number of cases to match.
A long `if`-`else if` chain becomes increasingly slower with each additional case
because essentially an O(n) _linear scan_ is performed.