From d531edc829101d9969273f7f0f920c05000d6e62 Mon Sep 17 00:00:00 2001 From: Benjamin Quorning Date: Sun, 2 Aug 2015 13:01:03 +0200 Subject: Save a string allocation inside loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the `tag_options` method, strings are continuously added to the `output` string. Previously, we concatenated two strings and added the generated string to `output`. By adding each of the strings to `output`, one after the other, we will save the allocation of that concatenated string. Benchmark: require 'benchmark/ips' sep = " ".freeze Benchmark.ips do |x| x.report("string +") { output = "" output << sep + "foo" } x.report("string <<") { output = "" output << sep output << "foo" } x.compare! end Results (Ruby 2.2.2): Calculating ------------------------------------- string + 88.086k i/100ms string << 94.287k i/100ms ------------------------------------------------- string + 2.407M (± 5.8%) i/s - 12.068M string << 2.591M (± 7.0%) i/s - 12.917M Comparison: string <<: 2591482.4 i/s string +: 2406883.7 i/s - 1.08x slower --- actionview/lib/action_view/helpers/tag_helper.rb | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'actionview') diff --git a/actionview/lib/action_view/helpers/tag_helper.rb b/actionview/lib/action_view/helpers/tag_helper.rb index 30af09cbac..2562504896 100644 --- a/actionview/lib/action_view/helpers/tag_helper.rb +++ b/actionview/lib/action_view/helpers/tag_helper.rb @@ -154,12 +154,17 @@ module ActionView options.each_pair do |key, value| if TAG_PREFIXES.include?(key) && value.is_a?(Hash) value.each_pair do |k, v| - output << sep + prefix_tag_option(key, k, v, escape) + output << sep + output << prefix_tag_option(key, k, v, escape) end elsif BOOLEAN_ATTRIBUTES.include?(key) - output << sep + boolean_tag_option(key) if value + if value + output << sep + output << boolean_tag_option(key) + end elsif !value.nil? - output << sep + tag_option(key, value, escape) + output << sep + output << tag_option(key, value, escape) end end output unless output.empty? -- cgit v1.2.3