From: Jacob Fugal Date: 2006-06-06T00:58:41+09:00 Subject: Re: This is brain dead, but is it stupid? On 6/4/06, Patrick Hurley wrote: > > So my multiline gsub tempstring " > width=\"replace_with_width\" height=\"replace_with_height\">\n" > > nastiness would become: > > > > @barString = %Q(\n) > > @htmlString << @barString % [barWidth,barHeight] > > Or you could just: > > @htmlString = %Q( height="#{barHeight}">\n) That doesn't benefit from the template string only needing to be built once. Compare these: template = 'T minus %d...' 15.downto(1) do |i| puts(template % i) end vs. 15.downto(1) do |i| puts "T minus #{i}" end I'll admit, I use the latter as well when I'm not concerned with the performance in that loop. It does look nicer and more compact. But I'm guessing[0] that the former will be significantly faster when 1) the number of iterations in the loop is high and 2) the template is moderately complex. Why? I assume that String#% is implemented in C using sprintf (or some cousin). So the performance of template % i is almost entirely related to one very well used and thus well optimized libc library call. "T minus #{i}" on the other hand involves parsing of the string to determine interpolation etc. This is probably also written in C, but involves more work than the quick sprintf call. Jacob Fugal [0] Yes, I'm guessing. I haven't actually benchmarked this or looked at the ruby sources, so I may be wrong.