From: ara.t.howard@... Date: 2006-07-28T01:20:30+09:00 Subject: Re: String#chop slow? REALLY slow? On Fri, 28 Jul 2006, Mat Schaffer wrote: > I just did a quick benchmark to prove something to myself. But I'd like to > get a sanity check from the people on the list. > > Basically I want to drop what will be a trailing "\n" from input. But it > appears that using String#[] and if statements is nearly 200 times more > efficient than chop. Which just seems really weird, so here's the > benchmark. Maybe I'm doing something wrong. > > Does this seem right? Anyone care to comment? > > ---- index_vs_chop.rb > > require 'benchmark' > > n = 100_000 > bigstring = "I am a big string " * 5_000 > > Benchmark.bmbm do |bench| > bench.report("Indexing") { > n.times do > bigstring[0..-1] > end > } > > bench.report("Chop") { > n.times do > bigstring.chop > end > } > end > > ---- end index_vs_shop.rb > > output: > > Rehearsal -------------------------------------------- > Indexing 0.100000 0.000000 0.100000 ( 0.102362) > Chop 7.190000 13.890000 21.080000 ( 22.477807) > ---------------------------------- total: 21.180000sec > > user system total real > Indexing 0.100000 0.000000 0.100000 ( 0.108777) > Chop 7.290000 14.050000 21.340000 ( 22.755782) on my node: harp:~ > ruby a.rb Rehearsal -------------------------------------------- Indexing 0.150000 0.000000 0.150000 ( 0.145923) Chop 4.210000 16.200000 20.410000 ( 20.910127) Chop2 4.210000 0.220000 4.430000 ( 4.536517) ---------------------------------- total: 24.990000sec user system total real Indexing 0.140000 0.000000 0.140000 ( 0.142257) Chop 0.110000 0.000000 0.110000 ( 0.104612) Chop2 0.150000 0.000000 0.150000 ( 0.152083) harp:~ > cat a.rb require 'benchmark' n = 100_000 bigstring = "I am a big string " * 5_000 Benchmark.bmbm do |bench| bench.report("Indexing") { n.times do bigstring[0..-1] end } bench.report("Chop") { n.times do bigstring.chop end } bench.report("Chop2") { n.times do bigstring = bigstring[0..-2] end } end -a -- we can never obtain peace in the outer world until we make peace with ourselves. - h.h. the 14th dali lama