Skip to content

Instantly share code, notes, and snippets.

@Daniel-Worrall
Created September 10, 2019 17:03
Show Gist options
  • Save Daniel-Worrall/10b93eb782d5b90b402a8ae508784524 to your computer and use it in GitHub Desktop.
Save Daniel-Worrall/10b93eb782d5b90b402a8ae508784524 to your computer and use it in GitHub Desktop.
Link Header Parsing Crystal Lang
crystal ./src/test.cr --release
{"hub" => "https://api.twitch.tv/helix/webhooks/hub",
"self" => "https://api.twitch.tv/helix/users/follows?first=1&from_id=1337"}
{"hub" => "https://api.twitch.tv/helix/webhooks/hub",
"self" => "https://api.twitch.tv/helix/users/follows?first=1&from_id=1337"}
{"hub" => "https://api.twitch.tv/helix/webhooks/hub",
"self" => "https://api.twitch.tv/helix/users/follows?first=1&from_id=1337"}
{"hub" => "https://api.twitch.tv/helix/webhooks/hub",
"self" => "https://api.twitch.tv/helix/users/follows?first=1&from_id=1337"}
1 325.74k ( 3.07µs) (± 7.74%) 2.16kB/op 2.30× slower
2 317.77k ( 3.15µs) (±11.71%) 2.16kB/op 2.36× slower
3 642.53k ( 1.56µs) (±14.37%) 832B/op 1.17× slower
4 749.58k ( 1.33µs) (± 9.98%) 0.99kB/op fastest
text = %(<https://api.twitch.tv/helix/webhooks/hub>; rel="hub", <https://api.twitch.tv/helix/users/follows?first=1&from_id=1337>; rel="self")
def parse_link_header(header)
links = {} of String => String
header.split(",").each do |part|
parts = part.split(";")
url = parts[0].gsub(/<(.*)>/, "\\1").strip
name = parts[1].gsub(/rel="(.*)"/, "\\1").strip
links[name] = url
end
links
end
def parse_link_header2(header)
header.split(",").each_with_object({} of String => String) do |link, links|
parts = link.split(";")
links[parts[1].gsub(/rel="(.*)"/, "\\1").strip] = parts[0].gsub(/<(.*)>/, "\\1").strip
end
end
def parse_link_header3(header)
header.split(",").each_with_object({} of String => String) do |link, links|
%r(<(\S+)>;\s+rel="(\S+)").match(link)
links[$2] = $1
end
end
def parse_link_header(header)
header.scan(/<(?<url>\S+)>;\s+rel=\"(?<name>\S+)\"/).each_with_object({} of String => String) do |link, links|
links[link["name"]] = link["url"]
end
end
pp parse_link_header(text)
pp parse_link_header2(text)
pp parse_link_header3(text)
pp parse_link_header4(text)
require "benchmark"
Benchmark.ips do |x|
x.report("1") { parse_link_header(text) }
x.report("2") { parse_link_header2(text) }
x.report("3") { parse_link_header3(text) }
x.report("4") { parse_link_header4(text) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment