如何在Ruby中以相反的顺序有效地处理字符串中的行?

时间:2014-12-04 00:03:01

标签: ruby string

我试图找到以相反顺序处理Ruby字符串中的行的最有效方法。这是我的两种方法:

def double_reverse(lines)
    lines.reverse!
    lines.each_line do |line|
        line.chomp!
        line.reverse!
        puts line
    end
end

def split_and_reverse(lines)
    lines.split("\n").reverse.each do |line|
        puts line
    end
end

if __FILE__ == $0
    lines = "This is the first line.\nThis is the second line"
    double_reverse(lines)
    lines = "This is the first line.\nThis is the second line"
    split_and_reverse(lines)
end

我想知道哪一个会使用更少的内存。还有其他方法可以使用更少的资源吗?我主要关注的是内存使用情况,但是如果我可以减少CPU使用率那么会很好。

编辑1:

在我的用例lines中可以有超过一百万行。如果split将内存使用量增加2倍,那对我来说肯定是个问题。但是,如果Ruby VM足够聪明,可以确定在调用lines之后不会使用split并释放它的内存,那么这可能不是问题。另一方面,就地reverse!方法在理论上似乎更有效,因为它可以在不复制lines的情况下完成。

1 个答案:

答案 0 :(得分:6)

尝试使用Array#reverse_each

lines.split("\n").reverse_each do |line|
    puts line
end

或者,如果保留内存是您的首要任务,那么使用String#rindex的方法可以相当确定,除了原始字符串之外没有进行任何额外的重要内存分配:

j = lines.length-1 # lines is the full string, not an array

while -1 <= j
  i = lines.rindex("\n", j) || -1
  line = lines[i+1..j]
  puts line
  j = i-1
end