【问题标题】:parallel assignment performance in RubyRuby 中的并行赋值性能
【发布时间】:2016-04-18 13:17:26
【问题描述】:

设置一个临时变量来交换数组中的两个元素似乎比使用并行赋值更有效。谁能帮忙解释一下?

require "benchmark"

Benchmark.bm do |b|
  b.report do
    40000000.times { array[1], array[2] = array[2], array[1] }
  end
end

Benchmark.bm do |b|
  b.report do
    40000000.times do
      t        = array[1]
      array[1] = array[2]
      array[2] = t
    end
  end
end

结果:

   user     system      total        real
   4.470000   0.020000   4.490000 (  4.510368)
   user     system      total        real
   3.220000   0.010000   3.230000 (  3.255109)

【问题讨论】:

标签: arrays ruby performance swap


【解决方案1】:

并行分配创建一个临时数组,然后将其分解。

GC.disable

def with_temp
  a = 1
  b = 2

  t = a
  a = b
  b = t
end

def with_parallel
  a = 1
  b = 2

  a, b = b, a
end

before_all = ObjectSpace.each_object(Array).count
with_temp
after_with_temp = ObjectSpace.each_object(Array).count
with_parallel
after_with_parallel = ObjectSpace.each_object(Array).count

GC.enable

puts after_with_temp - before_all          # => 1
puts after_with_parallel - after_with_temp # => 2

额外的Array 来自ObjectSpace.each_object(Array).count 本身。


另一种验证方式 - 查看说明:

puts RubyVM::InstructionSequence.compile("a = 1; b = 2; t = a; a = b; b = t").disasm
puts RubyVM::InstructionSequence.compile("a = 1; b = 2; a, b = b, a").disasm

==disasm:@>===========
本地表(大小:4,argc:0 [opts:0,rest:-1,post:0,block:-1,kw:-1@-1,kwrest:-1])
[ 4] a [ 3] b [ 2] t
0000 迹线 1 ( 1)
0002 putobject_OP_INT2FIX_O_1_C_
0003 setlocal_OP__WC__0 4
0005 放置对象 2
0007 setlocal_OP__WC__0 3
0009 getlocal_OP__WC__0 4
0011 setlocal_OP__WC__0 2
0013 getlocal_OP__WC__0 3
0015 setlocal_OP__WC__0 4
0017 getlocal_OP__WC__0 2
0019重复
0020 setlocal_OP__WC__0 3
0022离开


==disasm:@>===========
本地表(大小:3,argc:0 [opts:0,rest:-1,post:0,block:-1,kw:-1@-1,kwrest:-1])
[ 3] a [ 2] b
0000 迹线 1 ( 1)
0002 putobject_OP_INT2FIX_O_1_C_
0003 setlocal_OP__WC__0 3
0005 放置对象 2
0007 设置本地_OP__WC__0 2
0009 getlocal_OP__WC__0 2
0011 getlocal_OP__WC__0 3
0013 新数组 2
0015 重复
0016 展开数组 2, 0
0019 setlocal_OP__WC__0 3
0021 setlocal_OP__WC__0 2
0023离开

【讨论】:

  • 你能用指令序列或什么来改进你的答案吗?
  • "并行分配创建了一个临时数组,然后它会 splats。" – 这就是语言规范所说的应该发生。但是,任何 Ruby 实现都可以这样做,前提是用户无法观察到差异。我知道 JRuby 优化了中间 Array 的事实,我相信 Rubinius 和 IronRuby 也是如此。我怀疑,Topaz 和 MagLev 也可能会消除它。我猜 JRuby+Truffle 也是这样做的。 YARV 没有,但话又说回来,YARV 以速度慢和不执行任何优化而闻名,所以这不足为奇。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2011-07-04
  • 1970-01-01
相关资源
最近更新 更多