"David Garamond" <lists / zara.6.isreserved.com> schrieb im Newsbeitrag
news:41D15E03.5060803 / zara.6.isreserved.com...
> Stefan Schmiedl wrote:
> > On Tue, 28 Dec 2004 20:41:57 +0900,
> > David Garamond <lists / zara.6.isreserved.com> wrote:
> >
> >>Benchmark.measure shows that, on my box, I can do around 2000-2500 of
> >>roundtrip conversions per second, which is not too bad. But I wonder
if
> >>it can be made more efficient. The Ruby profiler shows the top 4
methods:
> >
> > I'm not sure on the effects it will have, but try extracting
> > the constants from your often-called methods. You're repeatedly
> > creating "the same objects" which might slow you down due to
> > unnecessary garbage collection.

Good point, Stefan!

> By constants, do you mean literal constants like '0-9a-z', 'a-z0-9', and
> 'a' in the code below?

Yes, I think so.

>    def to_base36
>      self.to_i.to_s(36).tr('0-9a-z', 'a-z0-9').rjust(25, 'a')
>    end
>
> Can't Ruby currently optimize those? I frankly don't want to have to do
> those kinds of optimization myself :-(

It does (by sharing the internal string buffer) but it still has to create
new String instances on each run:

>> 5.times { p 's'.id }
134947060
134946988
134696172
134690592
134690544
=> 5

If it would not do this, code like this would yield unexpected results:

>> 5.times { p 'abc'[1] += 1 }
99
99
99
99
99
=> 5

i.e. you'd see this instead:

>> 5.times { p 'abc'[1] += 1 }
99
100
101
102
103
=> 5


Kind regards

    robert