Compare commits

...

2 Commits

Author SHA1 Message Date
Parker Moore
ed2d30dc88 URL#generate_url_from_drop: optimizations to reduce object creation & speed things up 2017-08-02 20:18:11 -04:00
Parker Moore
3088032128 Hash#reduce vs Hash#each_with_object :thinking_face: 2017-08-02 17:58:34 -04:00
3 changed files with 44 additions and 17 deletions

View File

@@ -53,6 +53,7 @@ end
group :benchmark do
if ENV["BENCHMARK"]
gem "benchmark-ips"
gem "benchmark-memory"
gem "rbtrace"
gem "ruby-prof"
gem "stackprof"

View File

@@ -0,0 +1,36 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "benchmark/ips"
require "benchmark/memory"
GC.disable
PERIOD = "."
PROPERTY_AS_HASH = ["hello", "there_oh", "friends"]
property = "hello.there_oh.friends"
item = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
def candidate(property, item)
property.to_s.split(".".freeze).each_with_object(item) do |attribute, memo|
memo = memo[attribute]
end
end
def control(property, item)
property.to_s.split(".").reduce(item) do |subvalue, attribute|
subvalue[attribute]
end
end
Benchmark.ips do |x|
x.report("candidate") { candidate(property, item) }
x.report("control") { control(property, item) }
x.compare!
end
Benchmark.memory do |x|
x.report("candidate") { candidate(property, item) }
x.report("control") { control(property, item) }
x.compare!
end

View File

@@ -1,3 +1,5 @@
# frozen_string_literal: true
require "addressable/uri"
# Public: Methods that generate a URL for a resource such as a Post or a Page.
@@ -83,30 +85,18 @@ module Jekyll
# That should be :month and :day, but our key extraction regexp isn't
# smart enough to know that so we have to make it an explicit
# possibility.
def possible_keys(key)
if key.end_with?("_")
[key, key.chomp("_")]
else
[key]
end
end
def generate_url_from_drop(template)
template.gsub(%r!:([a-z_]+)!) do |match|
pool = possible_keys(match.sub(":".freeze, "".freeze))
key = match[1..-1]
key = match[1..-2] if !@placeholders.key?(key) && key.end_with?("_")
winner = pool.find { |key| @placeholders.key?(key) }
if winner.nil?
unless @placeholders.key?(key)
raise NoMethodError,
"The URL template doesn't have #{pool.join(" or ")} keys. "\
"The URL template doesn't have #{key} key. "\
"Check your permalink template!"
end
value = @placeholders[winner]
value = "" if value.nil?
replacement = self.class.escape_path(value)
match.sub(":#{winner}", replacement)
match.sub(":" + key, self.class.escape_path(@placeholders[key].to_s))
end.gsub(%r!//!, "/".freeze)
end