From: Robert Klemme Date: 2005-09-03T00:36:25+09:00 Subject: Re: Ruby-specific performance heuristics? ------=_NextPart_000_00D4_01C5AFE4.5216D700 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Ara.T.Howard wrote: > On Sat, 3 Sep 2005, Robert Klemme wrote: > >>> here's some things i think of: >> >> >> >>> - anchor every single regular expression : performance degrades >>> exponentially otherwise >> >> That's not possible - especially with String#scan. Sometimes you >> want all occurrences of something. > > true. however there nearly always __some__ anchor one can use: Ah, yes, I overlooked that one. > harp:~ > irb > irb(main):001:0> "foo bar".scan %r/ \b\w+ /x > => ["foo", "bar"] But does this really make such a big difference? Or does this depend on input sequence and rx? My quick hack test didn't show significant differences. 17:29:48 [ruby]: ruby bm-rx-anchor.rb Rehearsal ------------------------------------------------------- no anchor 4.469000 0.000000 4.469000 ( 4.465000) 1 anchor 4.515000 0.000000 4.515000 ( 4.525000) 2 anchors 4.500000 0.000000 4.500000 ( 4.520000) --------------------------------------------- total: 13.484000sec user system total real no anchor 4.500000 0.000000 4.500000 ( 4.509000) 1 anchor 4.484000 0.000000 4.484000 ( 4.494000) 2 anchors 4.531000 0.000000 4.531000 ( 4.531000) > a better thing would be to say "use an anchor unless you know exactly > why you shouldn't." Sounds good. >>> - compile regular expressions only once unless they require >>> variable substitution >> >> I guess you're talking about flag /o or storage of a regexp object >> somewhere which is really only needed if the regexp contains >> interpolation that you want to do only once. Otherwise a regexp >> *is* compiled only once and inline regexps are roughly as performant >> as a stored regexp and might be easier to read (not always). > > you are quite right - guy pointed this out to me once before - for > some reason my brain hasn't retained it though ;-) Well, repetition helps. :-)) Kind regards robert ------=_NextPart_000_00D4_01C5AFE4.5216D700 Content-Type: application/octet-stream; name="bm-rx-anchor.rb" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="bm-rx-anchor.rb" =0A= require 'benchmark'=0A= =0A= s =3D "foo bar;baz.snorkel"=0A= REP =3D 100000=0A= =0A= Benchmark.bmbm(20) do |bm|=0A= =0A= bm.report "no anchor" do=0A= REP.times { s.scan(/\w+/) {|m|} }=0A= end=0A= =0A= bm.report "1 anchor" do=0A= REP.times { s.scan(/\b\w+/) {|m|} }=0A= end=0A= =0A= bm.report "2 anchors" do=0A= REP.times { s.scan(/\b\w+\b/) {|m|} }=0A= end=0A= =0A= end=0A= ------=_NextPart_000_00D4_01C5AFE4.5216D700--