Skip to content

Instantly share code, notes, and snippets.

@rmm5t
Last active June 18, 2019 20:36
Show Gist options
  • Save rmm5t/302453b0eb84ac06ea32762abfdaa42d to your computer and use it in GitHub Desktop.
Save rmm5t/302453b0eb84ac06ea32762abfdaa42d to your computer and use it in GitHub Desktop.
Benchmarking tag vs content_tag vs string interpolation
require 'benchmark'
require 'action_view'
include ActionView::Helpers::TagHelper
include ERB::Util
def output_buffer=(s)
end
def output_buffer
end
def test_tag(body, cls, style)
tag(:div, class: cls, style: style) { body }
end
def test_content_tag(body, cls, style)
content_tag(:div, body, class: cls, style: style) { body }
end
def test_interpolation(body, cls, style)
"<div class='#{html_escape(cls)}' style='#{html_escape(style)}'>#{html_escape(body)}</div>".html_safe
end
def test_interpolation_cheat(body, cls, style)
"<div class='#{cls}' style='#{style}'>#{body}</div>".html_safe
end
n = 100_000
Benchmark.bmbm(15) do |x|
x.report("#tag") { n.times { test_tag("body", "foo", "color: white;") } }
x.report("#content_tag") { n.times { test_content_tag("body", "foo", "color: white;") } }
x.report("interpolation") { n.times { test_interpolation("body", "foo", "color: white;") } }
x.report("interpolation (cheating)") { n.times { test_interpolation_cheat("body", "foo", "color: white;") } }
end
# >> user system total real
# >> #tag 0.357679 0.000528 0.358207 ( 0.358630)
# >> #content_tag 0.648997 0.000605 0.649602 ( 0.650111)
# >> interpolation 0.328803 0.000452 0.329255 ( 0.329821)
# >> interpolation (cheating) 0.103121 0.000339 0.103460 ( 0.103557)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment