开发者

Ruby's variable swap: x,y = y,x -- seems to be slower with array references?

开发者 https://www.devze.com 2023-04-10 12:26 出处:网络
I was just testing out some array operations and doing the ol\'reverse-an-array problem (at high level) to see what the performance difference between Ruby\'s x,y = y,x swap and the typical use-a-temp

I was just testing out some array operations and doing the ol'reverse-an-array problem (at high level) to see what the performance difference between Ruby's x,y = y,x swap and the typical use-a-temp-variable-to-swap method:

# using Ruby's swap
z = arr.length-1
for x in 0..(z/2)
  arr[x], arr[z - x] = arr[z - x], arr[x]
end

# using standard temp var
z = arr.length-1
for x in 0..(z/2)
  temp = arr[x]
  arr[x] = arr[z - x]
  arr[z - x] = temp
end

Ruby's shortcut swap is about 40 percent slower. I'm guessing there's 开发者_StackOverflow中文版some kind of extra array reference that's done? But I don't see where that extra operation would be done...I just assumed Ruby did a temp-var-swap behind the scenes.

edit: This is the benchmark I'm using:

def speed_test(n)
  t = Time.now
  n.times do
    yield
  end
  Time.now - t
end

tn = speed_test(TIMES) do
  # code...
end

And the array is just:

arr = 10000.times.map


I'd guess that the problem is with your benchmark. Probably the first loop brings everything into the cache. Then the second loop runs identical code but it happens to be faster because the cache is fresh.

As a quick check of this, try reversing the order of the two loops!

0

精彩评论

暂无评论...
验证码 换一张
取 消