gpt4 book ai didi

ruby - Ruby 中的递归方法性能

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:02 25 4
gpt4 key购买 nike

我有以下用 Ruby 编写的递归函数,但我发现该方法运行速度太慢。我不确定这是否是正确的方法,所以请建议如何提高这段代码的性能。包括子目录在内的文件总数为 4,535,347

    def start(directory)
Dir.foreach(directory) do |file|
next if file == '.' or file == '..'
full_file_path = "#{directory}/#{file}"
if File.directory?(full_file_path)
start(full_file_path)
elsif File.file?(full_file_path)
extract(full_file_path)
else
raise "Unexpected input type neither file nor folder"
end
end

最佳答案

对于 450 万个目录,您最好使用专门的惰性枚举器,以便只处理您实际需要的条目,而不是生成 450 万个列表中的每一个,然后返回整个集合并遍历它完整。

这是文档中的示例:

class Enumerator::Lazy
def filter_map
Lazy.new(self) do |yielder, *values|
result = yield *values
yielder << result if result
end
end
end

(1..Float::INFINITY).lazy.filter_map{|i| i*i if i.even?}.first(5)

http://ruby-doc.org/core-2.1.1/Enumerator/Lazy.html

这不是一个很好的例子,顺便说一句:重要的部分是 Lazy.new() 而不是 Enumerator::Lazy 被猴子修补的事实。这是一个更好的例子恕我直言:

What's the best way to return an Enumerator::Lazy when your class doesn't define #each?

关于该主题的进一步阅读:

http://patshaughnessy.net/2013/4/3/ruby-2-0-works-hard-so-you-can-be-lazy

您可能要考虑的另一个选择是跨多个线程计算列表。

关于ruby - Ruby 中的递归方法性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23541086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com