From: Dennis Decker Jensen Date: 2001-05-06T03:54:46+09:00 Subject: [ruby-talk:14718] SV: Why's Ruby so slow in this case? Stefan Matthias Aust wrote: | I wonder whether there are some ways to optimize this code other than | to completely change the algorithm. Yes. | BTW, is there a way to profile just a part of a program? Yes: The Benchmark module. I benchmarked the different ways of iteration just to show you some valuable info... ---- require 'benchmark' include Benchmark n = 125 c = 10000 a=(0..n).to_a bm(12) do |t| t.report("range ") { c.times { (0..n).each {|x| x*x} } } t.report("array ") { c.times { a.each {|x| x*x} } } t.report("upto ") { c.times { 0.upto(n) {|x| x*x} } } t.report("downto") { c.times { n.downto(0) {|x| x*x} } } t.report("times ") { c.times { n.times {|x| x*x} } } t.report("while ") { c.times { x=0; while(x < n); x*x; x+=1; end } } t.report("until ") { c.times { x=0; until(x == n); x*x; x+=1; end } } end ----- The result: user system total real range 2.875000 0.000000 2.875000 ( 2.850000) array 2.670000 0.000000 2.670000 ( 2.690000) upto 2.658000 0.000000 2.658000 ( 2.640000) downto 2.666000 0.000000 2.666000 ( 2.690000) times 2.649000 0.000000 2.649000 ( 2.640000) while 2.700000 0.000000 2.700000 ( 2.690000) until 2.680000 0.000000 2.680000 ( 2.690000) | I tried to simulate the onmap() function in Squeak Smalltalk, a | language which is also just interpreted, garbage-collected, 100% | object oriented (and at least as cool as Ruby) and that system needs | just 0.13 s for 100.000 calls Impressive indeed. And Squak even has a reputation for being slow... | I'd like to understand why Ruby is 100 times slower than the slowest | Smalltalk. VisualWorks Smalltalk needs just 20ms for 100.000 calls, | BTW. It is my understanding that Matz is working on improving the interpreter regarding performance among other things. Aren't you Matz? Implementations of SmallTalk have for obvious reasons optimized message-passing since it affects the performance of the whole image. | If it's just the interpreter, wouldn't it be an idea to implement Ruby | on top of Squeak, using that obviously more sophisticated bytecode | interpreter, garbage collector and runtime system? Interesting idea. Best regards, Dennis Decker Jensen