在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,为什么“打开”总是相反更快?
我在Win7 Ruby1.9.3上测试了几次

解决方法

readlines和open.each_line只读取一次文件. Ruby将对IO对象进行缓冲,因此每次都会从磁盘读取一个块(例如64KB)数据,以最大限度地降低磁盘读取的成本.磁盘读取步骤应该没有多少时间差异.

当你调用readlines时,Ruby构造一个空数组[]并重复读取一行文件内容并将其推送到数组.最后它将返回包含文件所有行的数组.

当您调用each_line时,Ruby会读取一行文件内容并将其输出到您的逻辑中.处理完这一行后,ruby读取另一行.它重复读取行,直到文件中没有更多内容.

两种方法的区别在于,readlines必须将这些行附加到数组中.当文件很大时,Ruby可能必须复制底层数组(C级)以扩大其大小一次或多次.

挖掘源,readlines由io_s_readlines实现,调用rb_io_readlines. rb_io_readlines调用rb_io_getline_1来获取行,rb_ary_push将结果推送到返回的数组.

each_line由rb_io_each_line实现,它调用rb_io_getline_1以获取行,就像读取行一样,并使用rb_yield将行传递给逻辑.

因此,没有必要将行结果存储在每个行的增长数组中,不需要调整数组大小,复制问题.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...