我正在尝试找到以相反顺序处理 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 足够智能,可以确定在调用 split
并释放其内存后不会使用 lines
,那么这可能不是问题。另一方面,就地 reverse!
方法在理论上似乎更有效,因为它可以在不复制任何 lines
的情况下完成。
最佳答案
尝试使用 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
关于ruby - 如何在 Ruby 中以相反的顺序有效地处理字符串中的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27283999/