From: Caio Chassot Date: 2006-07-28T01:40:17+09:00 Subject: Re: String#chop slow? REALLY slow? On 2006-07-27, at 13:36 , Caio Chassot wrote: >> 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. > > Well, if you implement chop fully, you get very similar results: Ah, but rangeless indexing yields much much better results: RubyMate r4106 running Ruby v1.8.4 (/usr/local/bin/ruby) >>> untitled Rehearsal ------------------------------------------------- Indexing 0.110000 0.000000 0.110000 ( 0.151018) Chop 3.430000 7.920000 11.350000 ( 15.030196) Indexing crlf 0.110000 0.000000 0.110000 ( 0.128584) Chop crlf 3.430000 7.920000 11.350000 ( 14.815128) --------------------------------------- total: 22.920000sec user system total real Indexing 0.110000 0.000000 0.110000 ( 0.134087) Chop 3.430000 7.980000 11.410000 ( 14.305555) Indexing crlf 0.110000 0.000000 0.110000 ( 0.125122) Chop crlf 3.420000 7.990000 11.410000 ( 13.869411) --- require 'benchmark' n = 20_000 bigstring = "I am a big string " * 5_000 Benchmark.bmbm do |bench| bench.report("Indexing") { n.times do bigstring[-2,2] == "\r\n" ? bigstring[-2,2] : bigstring[-1,1] end } bench.report("Chop") { n.times do bigstring.chop end } bigstring << "\r\n" bench.report("Indexing crlf") { n.times do bigstring[-2,2] == "\r\n" ? bigstring[-2,2] : bigstring[-1,1] end } bench.report("Chop crlf") { n.times do bigstring.chop end } end