Bug or feature?

Can anybody explain to me what does it mean?

code ->
a1 = Array.new(1000000)
a2 = Array.new(1000000)
t = Time.now
1000000.times { |i| a1[i] = i; a2[i] = i }
print "1. Elapsed time: “, Time.now - t, " seconds\n”
t = Time.now
1000000.times { |i| a1[i], a2[i] = i, i }
print "2. Elapsed time: “, Time.now - t, " seconds\n”

results ->
ruby 1.8.6

  1. Elapsed time: 0.882 seconds
  2. Elapsed time: 11.436 seconds (!!!)
    jruby 1.1.1
  3. Elapsed time: 1.669 seconds
  4. Elapsed time: 2.249 seconds

2008/5/16 Igor G. [email protected]:

print "2. Elapsed time: “, Time.now - t, " seconds\n”

results →
ruby 1.8.6

  1. Elapsed time: 0.882 seconds
  2. Elapsed time: 11.436 seconds (!!!)
    jruby 1.1.1
  3. Elapsed time: 1.669 seconds
  4. Elapsed time: 2.249 seconds

I guess it’s because of the intermediate arrays that are created for
the second assignment.

Btw, here’s an even faster way:

13:10:16 JBoss$ /c/Temp/ass.rb
Rehearsal --------------------------------------------------------
a1[i] = i; a2[i] = i 1.188000 0.000000 1.188000 ( 1.185000)
a1[i], a2[i] = i, i 14.562000 0.000000 14.562000 ( 14.589000)
a1[i] = a2[i] = i 1.141000 0.000000 1.141000 ( 1.146000)
---------------------------------------------- total: 16.891000sec

                       user     system      total        real

a1[i] = i; a2[i] = i 1.156000 0.000000 1.156000 ( 1.150000)
a1[i], a2[i] = i, i 14.750000 0.000000 14.750000 ( 14.771000)
a1[i] = a2[i] = i 1.171000 0.000000 1.171000 ( 1.173000)
13:10:59 JBoss$ cat /c/Temp/ass.rb
#!/bin/env ruby

require ‘benchmark’

a1 = Array.new(1000000)
a2 = a1.dup

Benchmark.bmbm 20 do |x|

x.report “a1[i] = i; a2[i] = i” do
a1.size.times { |i| a1[i] = i; a2[i] = i }
end

x.report “a1[i], a2[i] = i, i” do
a1.size.times { |i| a1[i], a2[i] = i, i }
end

x.report “a1[i] = a2[i] = i” do
a1.size.times { |i| a1[i] = a2[i] = i }
end

end

Kind regards

robert

Robert K. wrote:

I guess it’s because of the intermediate arrays that are created for
the second assignment.

There isn’t such a problem in 1.9.0.