From: Kirk Haines Date: 2010-01-27T14:36:03+09:00 Subject: Re: Distressing Doc On Tue, Jan 26, 2010 at 6:20 PM, lalawawa wrote: > I was reading www.ruby-lang.org, and under "To Ruby From C and C++" it said > > * As of Ruby 1.8, code is interpreted at run-time rather than compiled to > any sort of machine- or byte-code. > > which sounds like a huge disadvantage compared to other languages.  I did > some testing and I get the impression that Ruby is compiling your code to > some form of compiled version in ram before it runs it. In the main Ruby 1.8 C implementation, it is not compiled. It parses the code into an abstract syntax tree, and then the interpreter executes the code based on that AST. In the main C 1.9.x implementation, one's code is compiled to a byte code format. > I made the following test programs > > ten_million.rb: > #!/usr/bin/ruby -w > > i = 10_000_000 > while i > 0 >    i -= 1 > end Idiom is important. A do nothing while loop: Benchmark.bm {|bm| bm.report {i = 10000000; while i > 0; i -= 1; end}} user system total real 1.840000 0.000000 1.840000 ( 1.841140) A faster way, in Ruby: Benchmark.bm {|bm| bm.report {10000000.downto(1) {}}} user system total real 0.490000 0.000000 0.490000 ( 0.492997) And it's still faster, even when we make sure the value of i is available in the block, so it's really quite equivalent to the while loop: Benchmark.bm {|bm| bm.report {10000000.downto(1) {|i|}}} user system total real 0.710000 0.000000 0.710000 ( 0.707342) In general, the MRI Ruby (the C implementation available from ruby-lang.org) interpreter for version 1.8.x will benchmark slower than Perl or Python on microbenchmarks, but as you can see above, choosing the right idiom for implementation can make a large difference. Kirk Haines