Created
April 23, 2018 12:16
-
-
Save crohr/8982c10ba4cd37cfedda14a68b579f30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: '[email protected]', 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 |
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
=> concat leads to a 15% drop in performance.