title: Nokogiri builder performance on huge XML?
body: <p>I need to build a huge XML file, about 1-50 MB. I thought that using builder would be effective enough and, well it is, somewhat. The problem is, after the program reaches its last line it doesn't end immediately, but Ruby is still doing something for several seconds, maybe garbage collection? After that the program finally ends.</p>
  
  <p>To give a real example, I am measured the time of building an XML file. It outputs 55 seconds (there is a database behind so it takes long) when the XML was built, but Ruby still processes for about 15 more seconds and the processor is going crazy.</p>
  
  <p>The pseudo/real code is as follows:</p>
  
  <pre><code>...
  builder = Nokogiri::XML::Builder.with(doc) do |xml|
    build_node(xml)
  end
  ...
  
  def build_node(xml)
    ...
    xml["#{namespace}"] if namespace  
    xml.send("#{elem_name}", attrs_hash) do |elem_xml|
    ...
      if has_children
        if type
          case type
            when XML::TextContent::PLAIN
              elem_xml.text text_content
            when XML::TextContent::COMMENT
              elem_xml.comment text_content
            when XML::TextContent::CDATA
              elem_xml.cdata text_content
           end
         else
           build_node(elem_xml)
         end
      end
    end
  end
  </code></pre>
  
  <p>Note that I was using a different approach using my own structure of classes, and the speed of the build was the same, but at the last line the program normally ended, but now I am forced to use Nokogiri so I have to find a solution.</p>
  
  <p>What I can do to avoid that X seconds long overhead after the XML is built? Is it even possible?</p>
  
  <p>UPDATE:</p>
  
  <p>Thanks to a suggestion from Adiel Mittmann, during the creation of my minimal working example I was able to locate the problem. I now have a small (well not that small) example demonstrating the problem.</p>
  
  <p>The following code is causing the problem:</p>
  
  <pre><code>xml.send("#{elem_name}_") do |elem_xml|
    ...
    elem_xml.text text_content #This line is the problem
    ...
  end
  </code></pre>
  
  <p>So the line executes the following code based on Nokogiri's documentation:</p>
  
  <pre><code>def create_text_node string, &amp;block
    Nokogiri::XML::Text.new string.to_s, self, &amp;block
  end
  </code></pre>
  
  <p><a href="http://nokogiri.org/Nokogiri/XML/Text.html#method-c-new" rel="nofollow">Text node creation code</a> gets executed then. So, what exactly is happening here?</p>
  
  <p>UPDATE 2:</p>
  
  <p>After some other tries, the problem can be easily reproduced by:</p>
  
  <pre><code>builder = Nokogiri::XML::Builder.new do |xml|
    0.upto(81900) do
      xml.text "test"
    end
  end
  puts "End"
  </code></pre>
  
  <p>So is it really Nokogiri itself? Is there any option for me?</p>