在ruby中,file.readlines.each并不比file.open.each_line快,为什
只是为了分析我的iis日志(BONUS:碰巧知道iislog是用ASCII编码的,错误的…)
这是我的ruby代码 1.readlines Dir.glob("*.log").each do |filename| File.readlines(filename,:encoding => "ASCII").each do |line| #comment line if line[0] == '#' next else line_content = line.downcase #just care about first one matched_keyword = keywords.select { |e| line_content.include? e }[0] total_count += 1 if extensions.any? { |e| line_content.include? e } hit_count[matched_keyword] += 1 unless matched_keyword.nil? end end end 2.open Dir.glob("*.log").each do |filename| File.open(filename,:encoding => "ASCII").each_line do |line| #comment line if line[0] == '#' next else line_content = line.downcase #just care about first one matched_keyword = keywords.select { |e| line_content.include? e }[0] total_count += 1 if extensions.any? { |e| line_content.include? e } hit_count[matched_keyword] += 1 unless matched_keyword.nil? end end end “readlines” read the whole file in mem,为什么“打开”总是相反更快? 解决方法
readlines和open.each_line只读取一次文件. Ruby将对IO对象进行缓冲,因此每次都会从磁盘读取一个块(例如64KB)数据,以最大限度地降低磁盘读取的成本.磁盘读取步骤应该没有多少时间差异.
当你调用readlines时,Ruby构造一个空数组[]并重复读取一行文件内容并将其推送到数组.最后它将返回包含文件所有行的数组. 当您调用each_line时,Ruby会读取一行文件内容并将其输出到您的逻辑中.处理完这一行后,ruby读取另一行.它重复读取行,直到文件中没有更多内容. 两种方法的区别在于,readlines必须将这些行附加到数组中.当文件很大时,Ruby可能必须复制底层数组(C级)以扩大其大小一次或多次. 挖掘源,readlines由io_s_readlines实现,调用 each_line由 因此,没有必要将行结果存储在每个行的增长数组中,不需要调整数组大小,复制问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |