|
Parsing SQL is made faster. Imagine a language with five keywords, for simplicity. keywords = ["AS", "FROM", "INSERT", "SELECT", "WHERE"];
tokens = [As, From, Insert, Select, Where];
Now you have a token that you need to interpret: let token_raw = "FROM";
let index = keywords.binary_search(token_raw);
let token = tokens[index];
As a binary search, that’s O(log N) string comparisons. In this worst case, it may try comparing with INSERT, then AS, then FROM before deciding index is 1, but for more keywords you have more comparisons.With perfect hashing, you devise a single hash function that hashes all possible values uniquely. Now we have something like this: tokens = {914576: As, 73932: From, 5791456: Insert, 21596: Select, 86548: Where};
… with all the numbers calculated by hashing the strings at compile time. Then, instead of O(log N) string comparisons, you only need one hash and one hash table lookup: let token_raw = "FROM";
let token = tokens[hash(token_raw)];
|