Skip to content

Instantly share code, notes, and snippets.

@lbguilherme
Created August 19, 2016 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbguilherme/7dba63104c4b44d3adcd5bcc9f9d7c20 to your computer and use it in GitHub Desktop.
Save lbguilherme/7dba63104c4b44d3adcd5bcc9f9d7c20 to your computer and use it in GitHub Desktop.
check every key 6.28M (±28.48%) 1.39× slower
trie lookup 8.7M (± 4.72%) fastest
COLORS = {
AliceBlue: "#f0f8ff",
AntiqueWhite: "#faebd7",
AntiqueWhite1: "#ffefdb",
AntiqueWhite2: "#eedfcc",
AntiqueWhite3: "#cdc0b0",
AntiqueWhite4: "#8b8378",
aquamarine1: "#7fffd4",
aquamarine2: "#76eec6",
aquamarine4: "#458b74",
azure1: "#f0ffff",
azure2: "#e0eeee",
azure3: "#c1cdcd",
azure4: "#838b8b",
}
struct NamedTuple(T)
macro fetch_trie_expand(keys, index, size)
{% if keys.size < 16 %}
{% for key in keys %}
return self[{{key}}] if {{key}} == key
{% end %}
{% else %}
{% chars = keys.map {|key| key.chars[index] }.uniq %}
case key[{{index}}]
{% for char in chars %}
when {{char}}
{% subkeys = keys.select {|key| key.chars[index] == char } %}
{% if index+1 == size %}
{% ans = subkeys[0] %}
{% if ans %}
return self[{{ans.id.symbolize}}]
{% end %}
{% else %}
fetch_trie_expand({{subkeys}}, {{index+1}}, {{size}})
{% end %}
{% end %}
end
{% end %}
end
def fetch1(key : String, &block)
{% for key in T %}
return self[{{key.symbolize}}] if {{key.stringify}} == key
{% end %}
yield
end
def fetch2(key : String, &block)
{% begin %}
{% keys = T.keys.map(&.stringify) %}
{% sizes = keys.map(&.size).uniq %}
case key.size
{% for size in sizes %}
when {{size}}
fetch_trie_expand({{ keys.select {|key| key.size == size} }}, 0, {{size}})
{% end %}
end
{% end %}
yield
end
end
require "benchmark"
keys = {{COLORS.keys.map(&.stringify)}}
glob = ""
Benchmark.ips do |x|
x.report("check every key") do
keys.each {|key| glob = COLORS.fetch1(key) {nil}}
end
x.report("trie lookup") do
keys.each {|key| glob = COLORS.fetch2(key) {nil}}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment