Many people are familiar with The Great Computer Language Shootout. I think it's a pretty cool site, despite whatever flaws it may have.
Last night someone popped into IRC wondering how Ruby's hash access compared to Perl's. According to the GLCS site (Hashes, Part I, not Part II), Perl is about twice as fast. This is the code:
hash = {}
for i in 1..n
hash['%x' % i] = 1
end
c = 0
n.downto 1 do |i|
c += 1 if hash.has_key? i.to_s
end
puts c
However, I decided to see if I could optimize the code a bit. Using some benchmarks and the profiler, I've discovered that "for" loops are faster than "downto", and "while" loops are faster than "for". The former is generally known, but the latter generally isn't. So, I rewrote it as this:
hash = {}
i = 0
while i < n
hash['%x' %i] = 1
i += 1
end
c = 0
while n >= 1
c += 1 if hash.has_key? i.to_s
n -= 1
end
puts c
I sent this code snippet to Doug Bagley, only to realize too late that he has abandoned the web site to work on other things. That's too bad, really. Maybe some other folks would like to pick it up? I'm hoping to at least bump up Ruby's rating over Python's, if not Perl's. :)