From: Robert Klemme Date: 2010-01-04T22:15:12+09:00 Subject: Re: Is ruby's regex slower? On 01/04/2010 10:22 AM, Ruby Newbee wrote: > On Mon, Jan 4, 2010 at 5:07 PM, Ayumu Aizawa wrote: >> Hi Jenn. >> >> Its interested ;) >> >> How's it? > > Thanks for the reminding, I got your meanings. > This time I used a compiled regex for both ruby and perl, the speed is > still different: > > > # cat regex_compile.rb > #!/usr/bin/ruby > > regex = /href="http:\/\/(.*?)\/.*" target="_blank"/ > > File.open("index.html") do |f| > f.each_line do |c| > puts $1 if c =~ regex > end > end "Compiling" regular expression does not bring any advantages. In fact, usually it's slower than using the regular expression inline as you did in your first example. The Ruby interpreter optimizes this already. If the speed difference does not bother it why bother discussing it? Btw, I'd probably formulate the regexp differently in order to avoid ".*?" which could be slow. Also, if you have a lot of slashes in the regexp the %r form comes in handy because you do not need all the escapes: File.foreach "index.html" do |line| puts $1 if %r{href="http://([^"/]*)/[^"]*"\s+target="_blank"} =~ line end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/