hashmatch
More efficient static &str matching when match #arm > 30.
Usage
use ;
// to avoid hash conflict
let res = match hash_str ;
assert_eq!;
The hash_arm! will compute each arm's hash during compiling, and expand it to
let res = match hash_str ;
Why hashmatch?
For current rustc, the string matching with large arm number is linear complexity O(n). While the matching complexity of hash (u64) is O(log(n)).
hashmatch achieves matching string's hash from 2 sides:
- For each match arm, using
hashmatch::hash_arm!to get string's static hash during compiling. - For the value to be matched, use
hashmatch::hash_strto get string's hash in runtime, which is consistent tohashmatch::hash_arm!.
But there is a potential risk when encounter DOS attacks.
Benchmark
You can run the benchmark in your environment by cargo bench, requiring ~20min.
The benchmark compared 4 methods:
match_str: Directly match string. O(n)match smatch_hash: (this) Compute string's hash, then matchu64. O(log(n))match hash_strlookup_phf: Create const hashmap in compiling time. O(1)const STRING_MAP: Map = phf_map! ; STRING_MAP.get.copiedlookup_lazy: Create lazy hashmap. O(1)static STRING_MAP: LazyLock = new; STRING_MAP.get.copied