Anyone of you has a few hints on how to speed up ruby code?
(Note - not writing it, but running it
)
I only have a few hints, like 5... would love to extend it.
So without further ado:
- Using << instead of += for Strings as += creates a new object
whereas << will simply work on the current object.
I'd replace that with the general rule to avoid object creation because that will cover more cases (Array#concat vs. Array#+, String#gsub! vs. String#gsub etc.).
- Use Inline C for critical methods (had to include that ;> )
You could argue that this does not speed up Ruby code but replaces it with something else. So it's questionable whether this item should be on the list.
- Reusing variable names might be better than using a lot of
different variables
Are you talking about a fact or a guess here? You write "might" - which indicates to me that this is not a proven fact.
- for is faster than .each on Arrays
- .last is faster than [0]
I guess you meant Array#last is faster than Array#[-1] or Array#first is faster than Array#[0].
- .zero? is faster than == 0
Interesting, I did not know that. But the difference is really small:
robert@fussel ~
$ time ruby -e '1_000_000.times { 0.zero? }'
real 0m0.748s
user 0m0.468s
sys 0m0.108s
robert@fussel ~
$ time ruby -e '1_000_000.times { 1.zero? }'
real 0m0.748s
user 0m0.483s
sys 0m0.124s
robert@fussel ~
$ time ruby -e '1_000_000.times { 0 == 0 }'
real 0m0.869s
user 0m0.561s
sys 0m0.108s
robert@fussel ~
$ time ruby -e '1_000_000.times { 1 == 0 }'
real 0m0.857s
user 0m0.562s
sys 0m0.124s
robert@fussel ~
$
If you know a few more hints, please add!
- freeze Strings that you are going to use as Hash keys.
Often bad design makes programs slow. While these are valid points often the bigger effect can be achieved by proper designing an application (i.e. use a Hash for frequent lookups instead of traversing an Aarry).
Kind regards
robert
···
On 17.03.2008 13:42, Marc Heiler wrote: