Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'erb'
require 'benchmark'
TEMPLATE = "<b><%= name %></b> in <%= city %>, <%= state_id %>"
LOCALS = { :name => 'Wes', :city => 'Seattle', :state_id => 'WA' }
def render_with_plain_erb
local_variables = Struct.new(*LOCALS.keys).new(*LOCALS.values)
ERB.new(TEMPLATE).result(local_variables.instance_eval { binding })
end
LOCAL_VARIABLE_CLASS_CACHE = Hash.new { |h, k| h[k] = Struct.new(*k) }
def render_with_plain_erb_and_class_caching
local_variables = LOCAL_VARIABLE_CLASS_CACHE[LOCALS.keys].new(*LOCALS.values)
ERB.new(TEMPLATE).result(local_variables.instance_eval { binding })
end
times = 100000
Benchmark.bm do |bm|
bm.report("ERB rendering using just ERB with no class cache") do
times.times { render_with_plain_erb }
end
bm.report("ERB rendering using just ERB and a class cache") do
times.times { render_with_plain_erb_and_class_caching }
end
end
ruby-1.8.7-p299 ➜ vcr git:(master) ✗ ruby benchmarks/erb_rendering.rb
user system total real
ERB rendering using just ERB with no class cache 19.230000 0.030000 19.260000 ( 19.266035)
ERB rendering using just ERB and a class cache 13.910000 0.000000 13.910000 ( 13.927047)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.