From: Rob Biedenharn Date: 2007-08-22T23:21:59+09:00 Subject: Re: How to "cast" in Ruby On Aug 22, 2007, at 8:49 AM, Kaldrenon wrote: > On Aug 22, 8:35 am, James Edward Gray II > wrote: >> On Aug 22, 2007, at 7:29 AM, Kaldrenon wrote: >> >>> On Aug 21, 10:11 pm, "Logan Capaldo" wrote: >>>> On 8/21/07, Kaldrenon wrote: >>>>> It's also exactly the same number of characters. >> >>>> I had to count to be sure, but you are indeed correct. :) I just >>>> think >>>> "#{foo}" looks busier than foo.to_s >> >>> By itself, I happen to agree, but I tend to dislike long method call >>> chains as in the original example. They both do the same thing, so >>> it's just a preference thing, I think. >> >> Well, one definitely has Ruby doing more work: >> >> #!/usr/bin/env ruby -wKU >> >> require "benchmark" >> >> TESTS = 1_000_000 >> Benchmark.bmbm do |results| >> results.report("iterpolation:") { TESTS.times { "#{TESTS}" } } >> results.report("to_s:") { TESTS.times { TESTS.to_s } } >> end >> # >> Rehearsal ------------------------------------------------- >> # >> iterpolation: 1.400000 0.000000 1.400000 ( 1.404947) >> # >> to_s: 0.820000 0.000000 0.820000 ( 0.817229) >> # >> ---------------------------------------- total: 2.220000sec >> # >> >> # >> user system total real >> # >> iterpolation: 1.400000 0.000000 1.400000 ( 1.395974) >> # >> to_s: 0.820000 0.000000 0.820000 ( 0.820689) >> >> __END__ > > Definitely a good thing to keep in mind, thanks James. However, that > only amounts to a difference of about .6 millionths of a second per > evaluation, so I'm thinking that there are a number of cases where > it's negligible? Look at it this way, you're doing (1.4/.82)-1 ~ .707 or 70.7% more work for this case. But what if the variable being interpolated is already a string? #!/usr/bin/env ruby -wKU require "benchmark" TESTS = 1_000_000 SUT = "This is a string under test" Benchmark.bmbm do |results| results.report("iterpolation:") { TESTS.times { "#{SUT}" } } results.report("to_s:") { TESTS.times { SUT.to_s } } end __END__ Rehearsal ------------------------------------------------- iterpolation: 0.860000 0.000000 0.860000 ( 0.859359) to_s: 0.290000 0.000000 0.290000 ( 0.294972) ---------------------------------------- total: 1.150000sec user system total real iterpolation: 0.860000 0.000000 0.860000 ( 0.858763) to_s: 0.310000 0.000000 0.310000 ( 0.303252) This is (.86/.31)-1 ~ 1.774 or 177.4% more work to interpolate a new string. Sure the numbers are small, but then how many times might a typical program do this kind of little extra effort? -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com