GLCS abandonment

djberg96 on 2003-01-07T14:20:18

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:

n = (ARGV.shift || 1).to_i

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:

n = (ARGV.shift || 1).to_i

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
Sending 10,000 as the number, I was able to drop the execution time from 9.5-10.5 seconds to 5-6 seconds (on my computer). At least, that's what the profiler told me.

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. :)