Try defining the variables used in a block before the block executes.
When iterating over a very large set of elements, you can improve
execution speed somewhat by predeclaring any iterator variables. In
the first example below, Ruby has to create new
x
and
y
variables
on each
iteration, but in the second version it doesn't. We'll use the
benchmark
package from the Ruby Application Archive to compare
the loops:
require "benchmark"
include Benchmark
n = 1000000
bm(12) do |test|
test.report("normal:") do
n.times do |x|
y = x + 1
end
end
test.report("predefine:") do
x = y = 0
n.times do |x|
y = x + 1
end
end
end
|
produces:
user system total real
normal: 2.450000 0.020000 2.470000 ( 2.468109)
predefine: 2.140000 0.020000 2.160000 ( 2.155307)
|