Bug or feature?

I

Igor Glukharev

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; a2 = i }
print "1. Elapsed time: ", Time.now - t, " seconds\n"
t = Time.now
1000000.times { |i| a1, a2 = 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
1. Elapsed time: 1.669 seconds
2. Elapsed time: 2.249 seconds
 
R

Robert Klemme

2008/5/16 Igor Glukharev said:
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; a2 = i }
print "1. Elapsed time: ", Time.now - t, " seconds\n"
t = Time.now
1000000.times { |i| a1, a2 = 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
1. Elapsed time: 1.669 seconds
2. 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; a2 = i 1.188000 0.000000 1.188000 ( 1.185000)
a1, a2 = i, i 14.562000 0.000000 14.562000 ( 14.589000)
a1 = a2 = i 1.141000 0.000000 1.141000 ( 1.146000)
---------------------------------------------- total: 16.891000sec

user system total real
a1 = i; a2 = i 1.156000 0.000000 1.156000 ( 1.150000)
a1, a2 = i, i 14.750000 0.000000 14.750000 ( 14.771000)
a1 = a2 = 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; a2 = i" do
a1.size.times { |i| a1 = i; a2 = i }
end

x.report "a1, a2 = i, i" do
a1.size.times { |i| a1, a2 = i, i }
end

x.report "a1 = a2 = i" do
a1.size.times { |i| a1 = a2 = i }
end

end

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top