From: Greg Hurrell Date: 2007-02-22T22:00:06+09:00 Subject: Re: Weird behaviour escaping special characters in a string On 21 feb, 19:45, James Edward Gray II wrote: > On Feb 21, 2007, at 12:36 PM, Austin Ziegler wrote: > > It's probably better to use a character class [\\'] instead of > alternation (\\|'). > > James Edward Gray II I did some quick and dirty benchmarks and using a character class is a little bit quicker. Interpolation ("\\#$1") is slower but more readable. I guess I'll stick with the character class and no interpolation though. require 'benchmark' include Benchmark bm(6) do |x| x.report('alternation') { 100_000.times { "'foo'".gsub(/(\\|')/, '\\\ \\1') } } x.report('char class') { 100_000.times { "'foo'".gsub(/[\\']/, '\\\\ \&') } } x.report('interpolation') { 100_000.times { "'foo'".gsub(/(\\|')/, "\ \#$1") } } x.report('interpolation with char class') { 100_000.times { "'foo'".gsub(/[\\']/, "\\#$&") } } end user system total real alternation 0.450000 0.000000 0.450000 ( 0.452661) char class 0.390000 0.000000 0.390000 ( 0.396193) interpolation 0.540000 0.010000 0.550000 ( 0.532106) interpolation with char class 0.480000 0.000000 0.480000 ( 0.485922)