Skip to content

Instantly share code, notes, and snippets.

@crohr
Created April 23, 2018 12:16
Show Gist options
  • Save crohr/8982c10ba4cd37cfedda14a68b579f30 to your computer and use it in GitHub Desktop.
Save crohr/8982c10ba4cd37cfedda14a68b579f30 to your computer and use it in GitHub Desktop.
require 'erb'
require 'benchmark'
require 'ostruct'
require 'action_view'
require 'rails'
include ActionView::Helpers::TagHelper
include ActionView::Helpers::TextHelper
include ActionView::Helpers::UrlHelper
data = OpenStruct.new name: 'Sample', email: 'sample@mail.com', list: %w(one two three)
@output = ''
def output_buffer=(string)
@output = string
end
def output_buffer
@output
end
erb_template = <<-ERB_TEMPLATE
<div>
<%= content_tag :p, data.name %>
<%= content_tag :p, data.email %>
<ul>
<% data.list.each do |l| %>
<%= content_tag :li, l %>
<% end %>
<span><%= link_to "link", "path" %></span>
</ul>
</div>
ERB_TEMPLATE
erb_template_concat = <<-ERB_TEMPLATE_CONCAT
<%= content_tag(:div) {
concat content_tag(:p, data.name)
concat content_tag(:p, data.email)
concat content_tag(:ul) {
data.list.each do |l|
concat content_tag(:li, l)
end
concat(content_tag(:span) do
link_to("link", "path")
end)
}
} %>
ERB_TEMPLATE_CONCAT
bind = binding
context = OpenStruct.new data: data
Benchmark.bmbm(10) do |b|
b.report(:erb_new) { (1..10000).each { ERB.new(erb_template, 0, '', '@output').result bind } }
b.report(:erb_concat) { (1..10000).each{ ERB.new(erb_template_concat, 0, '', '@output').result bind } }
end
@crohr
Copy link
Author

crohr commented Apr 23, 2018

$ ruby bm.rb 
Rehearsal ----------------------------------------------
erb_new      0.930000   0.050000   0.980000 (  1.087650)
erb_concat   1.100000   0.030000   1.130000 (  1.252630)
------------------------------------- total: 2.110000sec

                 user     system      total        real
erb_new      0.970000   0.010000   0.980000 (  1.077419)
erb_concat   1.120000   0.000000   1.120000 (  1.256709)

=> concat leads to a 15% drop in performance.

@kriom
Copy link

kriom commented Apr 23, 2018

Hi @crohr !

Thanks for this Benchmark !

With RubyOnRails it is natively possible to define views with .ruby extension.
If you prefer .rb you add this to an initializer:

ActionView::Template.register_template_handler(:rb, :source.to_proc)

Then these views will be rendered without using ERB

views/path/my_veiw.html.ruby
views/path/my_veiw.html.rb

Could you make the same test without using ERB for .ruby/.rb views?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment