[Newbie] The pickaxe book and benchmark

Hello,

I was reading the pickaxe book and then I arrived to the chapter

“When trouble strikes” in the Benchmark section.

I have this code:

#!/usr/bin/ruby -w
require ‘benchmark’
include Benchmark

LOOP_COUNT = 1_000_000

bm(12) do |test|
test.report(“normal:”) do
LOOP_COUNT.times do |x|
y = x +1
end
end
test.report(“predefine:”) do
x = y = 0
LOOP_COUNT.times do |x|
y = x + 1
end
end
end

The “predefine” test is more fast than the “normal”. Why?
The only difference that I see is x = y = 0 but I don’t understand

thanks!

                               Rafael G.

Rafa G. wrote:

LOOP_COUNT.times do |x|
  y = x + 1
end

end
end

The “predefine” test is more fast than the “normal”. Why?
The only difference that I see is x = y = 0 but I don’t understand

thanks!
Because of scope. In the second test, x and y are defined in the scope
outside the code block, and the block uses the outside variables. In the
first block, the variables are created for each iteration of the loop.

Thanks!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs