首页 > 解决方案 > Rails - file.readlines 与 file.gets

问题描述

我想从 SFTP 服务器读取文件行。文件中有超过 100000 行。

我以两种方式阅读。

Net::SSH.start(setting.host, setting.user,
  {
    :key_data => [ key ],
    :keys => [],
    :keys_only => true
  }
) do |ssh|
  ssh.sftp.connect do |sftp|
    sftp.dir.foreach(src_dir) do |entry|
      if entry.name.include? today
        filename = "#{src_dir}/#{entry.name}"
        sftp.file.open(filename, "r") do |f|

          # Way 1
          f.readlines.each do |line|
            parse(line)
          end

          # Way 2
          while line = f.gets do
            parse(line)
          end
        end
      end
    end 
  end
end

我想知道哪种方式在内存使用方面更好。

标签: ruby-on-railsrubymemory

解决方案


文档怎么说?(请注意,它File是 的子类IO。方法#readlines#gets定义在 上IO。)

IO#readlines

读取所有行 [...],并以数组的形式返回它们。

IO#gets

从 I/O 流中读取下一个“行”。

因此,我希望后者在内存使用方面会更好,因为它不会将整个文件加载到内存中。


推荐阅读