From: Robert Klemme Date: 2008-05-30T15:34:50+09:00 Subject: Re: Strings, postgresql and gsub On 30.05.2008 03:16, Peņa wrote: > From: Robert Klemme [mailto:shortcutter@googlemail.com] > # 2008/5/29 Peņa, Botp : > # > faq. try the block form for less headache. > # > # ... and less performance. > > by how much? > > Benchmark.realtime{9999.times{s.gsub(/'/){"\\'"}}} > #=> 0.139999866485596 > Benchmark.realtime{9999.times{s.gsub(/'/,"\\\\'")}} > #=> 0.108999967575073 robert@fussel ~ $ ruby -r benchmark < Benchmark.bmbm do |r| > r.report "block" do > 1_000_000.times { "foobarbaz".gsub(/o/){'X'} } > end > r.report "str" do > 1_000_000.times { "foobarbaz".gsub(/o/,'X') } > end > end > XXX Rehearsal ----------------------------------------- block 10.438000 0.000000 10.438000 ( 10.583000) str 5.109000 0.000000 5.109000 ( 5.310000) ------------------------------- total: 15.547000sec user system total real block 10.578000 0.000000 10.578000 ( 10.816000) str 5.219000 0.000000 5.219000 ( 5.326000) robert@fussel ~ $ Similar results for 1.8 and 1.9. > # ... Proper escaping is the way to go. > > yeh, while losing flexibility/easeofuse :( that's what's giving me the headache (especially now that i have four eyes and my head's getting heavier. "Proper" is relative, pick one that works best for you :) My reasoning is as follows: you need to use the block form if you need to _calculate_ the replacement string for every match. If the replacement follows a particular pattern or is constant use the string form. Kind regards robert