On 9/27/09, Ehsanul Hoque <ehsanul_g3 / hotmail.com> wrote: >> Is it the case that such "anonymous" objects like regexps (maybe also >> strings?) are re-created whenever the code snippet they are defined in >> is executed? If so, is there a convenient way of preventing this? Is >> this only the case for regexps or also for strings and other objects? >> (Why is it the case at all - I can't make any sense of it?) I would >> like to learn how I can write Ruby code that is reasonably efficient >> in this regard because the impact on execution time in the described >> situation was so immense. (I'm currently using Ruby 1.9.1.) > > Yes, indeed a new object is indeed created every time an anonymous object is > created. The only core object I know of for which this is not true is the > symbol, which is basically an immutable string. There may be others I'm not > aware of though. I suppose your code shows that there just might be a need > for the symbol equivalent of a regexp. Actually, I believe that regexp literals are created only once even if they're executed multiple times. The exception to this would be when you use #{} within a regexp... that forces ruby to not only create a new object each time the regexp literal is executed, it has to recompile the regexp each time.... and that is really slow. You can bypass this behavior by using the o regexp option, but that only works right if the value of the inclusion (what's inside #{}) is guaranteed to be the same on each execution. Thomas, are you using #{} within your regexps? If so, you should try sticking an o on the end of each one; that will probably solve your performance problem. for instance x =~ /foo#{bar}/o instead of x =~ /foo#{bar}/