From: Eric Hodel Date: 2006-09-05T09:10:51+09:00 Subject: Re: Compiling Regexp only once On Sep 4, 2006, at 4:29 PM, Rick DeNatale wrote: > On 9/4/06, Robert Klemme wrote: > >> Note though that it's usually faster to have a regexp in line. So in >> your case you might have a method that does the line parsing (or >> multiple line parsing) and that's where you can put the inline regexp >> for max efficiency. > > Robert, > > I'm not sure what you mean by inline, do you mean a regexp literal > like > /[ABC]/ vs. RegEx.new('/[ABC]/') if so that's not clear. > > See my benchmarks on the thread about "Ordered contrast for String or > Array," where changing a literal /./ to a constant set to > RegEx.new('/./') caused a 200 fold performance increase. Those aren't the same regular expression. I expect that your benchmark is flawed. Looking at it: $ ruby str = "abcdefghijklmnopqrstuvwxyz" * 5 RE = Regexp.new('/./') p str.scan RE -:3: warning: parenthesize argument(s) for future version p str.scan /./ -:4: warning: parenthesize argument(s) for future version [] ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] Also, you forgot about using String#split (but it is slower than unpack and scan). $ ruby -e 'p Regexp.new("/./").source, /./.source' "/./" "." The correct way to construct a Regexp from Regexp.new is to omit // in the pattern when it is a String. > Not that you always want to do that, benchmarking always beats > rules of thumb. Benchmarking and testing beat rules of thumb. -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com