Skip to content

Instantly share code, notes, and snippets.

@flavorjones
Last active May 18, 2023 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flavorjones/4875b772b7517185913bded8e18b1ed5 to your computer and use it in GitHub Desktop.
Save flavorjones/4875b772b7517185913bded8e18b1ed5 to your computer and use it in GitHub Desktop.
#! /usr/bin/env ruby
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "builder"
gem "nokogiri"
gem "benchmark-ips"
end
require "builder"
require "nokogiri"
require "benchmark/ips"
N = 100
# using Builder::XmlMarkup, build an XML document representing attributes of a person
def builder_person
xml = Builder::XmlMarkup.new
xml.people do |p|
N.times do
xml.person do |p|
p.name "John Doe"
p.age 42
p.address do |a|
a.street "123 Main Street"
a.city "Anytown"
end
end
end
end
end
# using Nokogiri::XML::Builder, build an XML document representing attributes of a person
def nokogiri_person
Nokogiri::XML::Builder.new do |xml|
xml.people do
N.times do
xml.person do |p|
p.name "John Doe"
p.age 42
p.address do |a|
a.street "123 Main Street"
a.city "Anytown"
end
end
end
end
end.to_xml
end
# use Nokogiri's bare API to build an XML document representing attributes of a person
def nokogiri_raw_person
doc = Nokogiri::XML::Document.new
doc.root = doc.create_element("people")
N.times do
doc.root.add_child(doc.create_element("person")).tap do |p|
p.add_child(doc.create_element("name", "John Doe"))
p.add_child(doc.create_element("age", 42))
p.add_child(doc.create_element("address")).tap do |a|
a.add_child(doc.create_element("street", "123 Main Street"))
a.add_child(doc.create_element("city", "Anytown"))
end
end
end
doc.to_xml
end
puts RUBY_DESCRIPTION
# pp builder_person
# pp nokogiri_person
# pp nokogiri_raw_person
Benchmark.ips do |x|
x.report("Builder") { builder_person }
x.report("Nokogiri::XML::Builder") { nokogiri_person }
x.report("Nokogiri::XML::Document") { nokogiri_raw_person }
x.compare!
end
$ ruby ./issues/benchmark-xml-builders.rb
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-linux]
Warming up --------------------------------------
Builder 54.000 i/100ms
Nokogiri::XML::Builder
47.000 i/100ms
Nokogiri::XML::Document
47.000 i/100ms
Calculating -------------------------------------
Builder 539.632 (± 7.6%) i/s - 2.700k in 5.034709s
Nokogiri::XML::Builder
475.543 (± 8.6%) i/s - 2.397k in 5.086260s
Nokogiri::XML::Document
722.282 (± 5.7%) i/s - 3.619k in 5.028424s
Comparison:
Nokogiri::XML::Document: 722.3 i/s
Builder: 539.6 i/s - 1.34x slower
Nokogiri::XML::Builder: 475.5 i/s - 1.52x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment