On Mon, 1 Nov 2004, Joel VanderWerf wrote:

> Just a little correction to a worthy post...

thanks

> John Carter wrote:
> ...
>>   class BigExpensiveMadeOften
>>     def initialize( unique_name)
>>       # Big expensive computation
>>     end
>>

make that
     @@memo = Hash.new {|hash,key| hash[key] = BigExpensiveMadeOften.new( key)}


Reminder for the day for not so Nubies...

Every reference to a string is a String.new, so sometimes factoring out string constants out of inner loops can be a big win...


(1..1000).each do |i|
   if (i % 2) == 0
     a << 'Was even'
   else
     a << 'Was odd'
end


Creates 500 indentical instances of 'Was even' and 500 identical instances of 'Was odd'

EVEN_MSG = 'Was even'
ODD_MSG = 'Was odd'

(1..1000).each do |i|
   if (i % 2) == 0
     a << EVEN_MSG
   else
     a << ODD_MSG
end


Saves you 998 strings



=======foo.rb==========
a=[]
(1..1000).each do |i|
   a << 'This is a great big string'
end

p a[100]
a[100][0] = 32


p a[99]
p a[100]
p a[101]

b = "This is an long string"

a=[]
(1..1000).each do |i|
   a << b
end

p a[100]
a[100][0] = 32


p a[99]
p a[100]
p a[101]
====================
ruby -w foo.rb
"This is a great big string"
"This is a great big string"
" his is a great big string"
"This is a great big string"
"This is an long string"
" his is an long string"
" his is an long string"
" his is an long string"




John Carter                             Phone : (64)(3) 358 6639
Tait Electronics                        Fax   : (64)(3) 359 4632
PO Box 1645 Christchurch                Email : john.carter / tait.co.nz
New Zealand

The universe is absolutely plastered with the dashed lines exactly one
space long.