Erudition and Inanity

brian guthrie blogs

Speeding up ActiveResource

Posted by Brian Guthrie Fri, 30 May 2008 02:09:00 GMT

I’ve been knocking around ways to speed up ActiveResource recently. My colleague Tim Cochran discovered that you take a big performance hit from Hash.from_xml (which uses XmlSimple to transform the parsed XML into a hash with a particular structure) and I’ve knocked up a couple of alternatives, one for libxml-ruby and one for Hpricot. I haven’t packaged them up into a plugin yet, but I’ll attach the raw source, and hopefully that’ll help someone.

There’s already at least one other attempt to adapt libxml to ActiveResource floating around, but as far as I can tell it doesn’t work: it doesn’t place the resulting XML in a form that allows ActiveSupport to successfully undasherize the keys, deserialize primitives by their type attribute, and place the result in an ActiveResource object (though it is of course possible that I configured the library incorrectly). I’ve tested the parsers below against the corresponding XmlSimple call and I know that they succesfully deserialize into the desired end result.

  • libxml (extends XML::Document with a to_hash method, roughly 5-10x faster than XmlSimple)
  • hpricot (extends Hpricot::Doc with a to_hash method, roughly 3-5x faster than XmlSimple)

Use them like this:

module ActiveSupport
  module CoreExtensions
    module Hash
      module Conversions
        module ClassMethods
          # libxml
          def from_xml(xml)
            xml.gsub!(/\s*\n\s*/, '')
            typecast_xml_value(undasherize_keys(XML::Parser.string(xml).parse.to_hash))
          end

          # hpricot
          def from_xml(xml)
            typecast_xml_value(undasherize_keys(Hpricot.XML(xml).to_hash))
          end
        end
      end
    end
  end
end

Posted in | no comments | Tags , , , , | atom

Trackbacks

Use the following link to trackback from your own site:
http://blog.brianguthrie.com/trackbacks?article_id=speeding-up-activeresource&day=29&month=05&year=2008

Comments

Leave a response

Leave a comment