ruby-on-rails - 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
我想知道哪种方式在内存使用方面更好。
解决方案
文档怎么说?(请注意,它File
是 的子类IO
。方法#readlines
和#gets
定义在 上IO
。)
读取所有行 [...],并以数组的形式返回它们。
从 I/O 流中读取下一个“行”。
因此,我希望后者在内存使用方面会更好,因为它不会将整个文件加载到内存中。
推荐阅读
- c# - 为什么 HtmlElementEventArgs.ToElement 返回 null?
- php - 这个函数语法在 php 中有什么作用?
- python - 在 Django Admin 中使用外键关系同时保存两条或多条记录
- javascript - react中的`PropTypes.node`和`PropTypes.any`有什么区别?
- mysql - 按 id 排序的复合索引上的并发查询非常慢
- c# - 使用 WebGrid Helper 时如何使列可见
- javascript - 尝试匹配字符串,包括字符串中的引号
- google-apps-script - 尝试设置 Google 表单测验分数时出错
- android - 一些高版本的OPPO和VIVO系统打不开debug apk?
- django - 根据请求在 django-filter ModelChoiceFilter (select) 和 ModelMultipleChoiceFilter (multi-select) 菜单中自定义查询集