红宝石循环重构

时间:2009-04-27 20:16:16

标签: ruby arrays refactoring

我有一个看起来像这样的循环

def slow_loop(array)
 array.each_with_index do |item, i|
   next_item = array[i+1]
   if next_item && item.attribute == next_item.attribute
     do_something_with(next_item)
   end
 end
end

除了改变调用do_something_with的方式之外,我怎样才能使这个表现更好?

THX,

-C

P.S。

由于看起来这是一个'O(n)'操作,显然没有在这里获得性能,所以我选择的答案就是使用已经封装了这个操作的ruby方法。感谢大家的帮助

3 个答案:

答案 0 :(得分:6)

正如其他人所说,你不会提高性能,但你可以更清洁地做到这一点:

array.each_cons(2) do |a, b|
  do_something_with(b) if a == b
end

答案 1 :(得分:2)

do_something_with的表现是主要因素。其他任何东西都是微优化。

这应该是O(n),你可以找到一种方法来避免最后的检查,但在宏观计划中这不会那么昂贵。

答案 2 :(得分:0)

我倾向于同意Garry的优化潜力,但它肯定可以写得更简单。

prev_attr = nil
my_array.each |item|
  do_something_with(item) if prev_attr and prev_attr == item.attribute
  prev_attr = item.attribute
end