为什么这个XML解析Ruby代码在禁用GC时运行得更慢?

mjk*_*kpl 5 ruby performance garbage-collection

我有一段代码使用libxml-rubygem 解析500 MB的XML文件.让我感到惊讶的是,这个代码在禁用 GC时运行速度较慢,这似乎是违反直觉的.可能是什么原因?我有足够的内存,系统没有交换.

require 'xml'

#GC.disable

@reader = XML::Reader.file('books.xml', :options => XML::Parser::Options::NOBLANKS)

@reader.read 
@reader.read

while @reader.name == 'book'
  book_id = @reader.get_attribute('id')
  @reader.read

  until @reader.name == 'book' && @reader.node_type == XML::Reader::TYPE_END_ELEMENT
    case @reader.name
    when 'author'
      author = @reader.read_string
    when 'title'
      title = @reader.read_string
    when 'genre'
      genre = @reader.read_string
    when 'price'
      price = @reader.read_string
    when 'publish_date'
      publish_date = @reader.read_string
    when 'description'
      description = @reader.read_string
    end
    @reader.next
  end

  @reader.read      

end
@reader.close
Run Code Online (Sandbox Code Playgroud)

以下是我得到的结果:

ruby     gc on   gc off
2.2.0    16.93s  18.81s
2.1.5    16.22s  18.58s
2.0.0    17.63s  17.99s
Run Code Online (Sandbox Code Playgroud)

为什么禁用垃圾收集器?我在Ruby性能优化书中读到Ruby很慢,主要是因为程序员不考虑内存消耗,这使得垃圾收集器使用了大量的执行时间.因此,只要系统没有交换,关闭GC就会立即加快速度(以内存使用为代价).

我想看看我的XML解析模块是否可以改进,所以我开始通过禁用GC来试验它,这让我遇到了这个问题.我预计在禁用GC的情况下会显着提高速度,但我却反其道而行之.我知道差异并不大,但这对我来说仍然很奇怪.

libxml-rubygem使用本机C LibXML实现 - 这可能是原因吗?

我使用的文件是books.xml从某些Microsoft文档下载的手动多重样本:

<catalog>
 <book id="bk101">
  <author>John Doe</author>
  <title>XML for dummies</title>
  <genre>Computer</genre>
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date>
  <description>Some description</description>
 </book>
 ....
</catalog>
Run Code Online (Sandbox Code Playgroud)

我的设置:OS X Yosemite,Intel Core i5 2.6 GHz,16GB RAM.

谢谢你的任何建议.