Optimize and Ruby in the same sentence. Since I know very little about Ruby inner workings I'll tell you the most common optimizations or things to avoid. Division operations (for floats avoid multiplication as well), oh and conditionals. The way I remember it from class was that the CPU does branch prediction and assumes its true and false and partially does the work in either direction. It discards the work that was wrong. Although it probably has some preference hopefully if the wind blows in a particular direction. I'm sure if Brewmeister, Prexus or etheon see this they'll have much more information on your request. Reducing code size however.
Conditional statements:
Is the same as:
Make use of the ternary statement.
if test
a = 1
else
a = 0
end
Is the same as:
Simple one line iterators:
collection.each do |item|
do(item)
end
Is the same as:
collection.each {|item| do(item)}
Multiple assignment:
Is the same as:
Or with different values:
Is the same as:
Oh a neat little trick for multiplying or dividing by a power of two. Bit shifting a number by 1 is the same as a multiplication/division by two.
00000110 = 6
If I shift it right once
00000011 = 3
If I shift it left twice which is like multiplying by 4
00001100 = 12
By the way its the ">>" "<<" operators.
a = 12
a >>= 1
p a # prints 6
a <<= 2
p a # prints 24
More huh? Um... Constant values are much more appreciated than dynamic values speaking from the cpu's point of view. They're less time spent in a calculation if the code already has the numbers laid out for the cpu. For example:
toad = 'A frog but smaller'
p toad
The above code is resolved at runtime. That will first create a local variable and save a string of data to it and then prints it. When it goes to print it has to perform a variable lookup and resolve it.
TOAD = 'A frog but smaller'
p TOAD
Hopefully during compilation rather than runtime all instances of TOAD are replaced with the string of data and that saves the cpu the time of having to look it up during runtime.
I don't know if Ruby in fact does this but in C such a thing exists. After writing all that I truly wonder how much time you actually save...
Good luck with it luis! :thumb: