From: Brian Mitchell Date: 2006-04-13T03:55:02+09:00 Subject: Re: First script seems slow - What's a better way to write t 2006/4/12, Logan Capaldo : > You use this idiom: > > class SomeClass > def initialize > @some_re = /some_re/ > end > def some_method > # do stuff with @some_re > end > end Actually, Ruby is quite smart in some cases.. Try the following: @re = /^\w+-\w+$/ # Some random expression def foo(str) str =~ @re end def bar(str) str =~ /^\w+-\w+$/ end def qux(str) str =~ Regexp.new("/^\w+-\w+$/") end require 'benchmark' include Benchmark bm(16) do |test| test.report("foo") do 1_000_000.times {foo("abc-xyz")} end test.report("bar") do 1_000_000.times {bar("abc-xyz")} end test.report("qux") do 1_000_000.times {qux("abc-xyz")} end end I get something like this on 1.8 cvs: user system total real foo 4.920000 0.080000 5.000000 ( 5.581873) bar 4.610000 0.060000 4.670000 ( 5.457461) qux 15.280000 0.280000 15.560000 ( 17.514639) So ruby actually shares a single compiled Regexp object in bar's case (as can also be proven by counting Regexp's in ObjectSpace with the GC disabled). Brian.