From: Caio Chassot Date: 2006-07-28T01:36:42+09:00 Subject: Re: String#chop slow? REALLY slow? > 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: RubyMate r4106 running Ruby v1.8.4 (/usr/local/bin/ruby) >>> untitled Rehearsal ------------------------------------------------- Indexing 1.790000 3.950000 5.740000 ( 7.099300) Chop 1.680000 3.930000 5.610000 ( 7.135508) Indexing crlf 1.780000 3.970000 5.750000 ( 6.895291) Chop crlf 1.670000 3.930000 5.600000 ( 6.573193) --------------------------------------- total: 22.700000sec user system total real Indexing 1.780000 3.980000 5.760000 ( 7.033924) Chop 1.670000 3.970000 5.640000 ( 7.297766) Indexing crlf 1.790000 4.020000 5.810000 ( 8.969243) Chop crlf 1.680000 4.000000 5.680000 ( 7.480123) --- require 'benchmark' n = 10_000 bigstring = "I am a big string " * 5_000 Benchmark.bmbm do |bench| bench.report("Indexing") { n.times do bigstring[0..-2] == "\r\n" ? bigstring[0..-2] : bigstring[0..-1] end } bench.report("Chop") { n.times do bigstring.chop end } bigstring << "\r\n" bench.report("Indexing crlf") { n.times do bigstring[0..-2] == "\r\n" ? bigstring[0..-2] : bigstring[0..-1] end } bench.report("Chop crlf") { n.times do bigstring.chop end } end