secret
Created

  • Download Gist
xpath-vs-css.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
require "nokogiri"
require "benchmark"
 
 
doc = Nokogiri.XML <<-XML
<Listings>
<Listing>
<Location>
<StreetAddress>123 Main St</StreetAddress>
<UnitNumber>2F</UnitNumber>
<City>Anytown</City>
<State>NY</State>
<Zip>10000</Zip>
</Location>
</Listing>
<property>
<Location>
<StreetAddress>321 Main St</StreetAddress>
<UnitNumber>2F</UnitNumber>
<City>Anytown</City>
<State>NY</State>
<Zip>10000</Zip>
</Location>
</property>
</Listings>
XML
 
 
ITERATIONS = 1000
 
 
Benchmark.bmbm do |x|
 
x.report("xpath") do
ITERATIONS.times do
doc.xpath("//*[self::Location or self::property]").map do |item|
item.xpath("./*[self::StreetAddress or self::AlternativeStreetAddress]").text
end
end
end
 
x.report("css") do
ITERATIONS.times do
doc.css("Location,property").map do |item|
item.css("StreetAddress,AlternativeStreetAddress").text
end
end
end
 
x.report("find") do
ITERATIONS.times do
doc.search("Location", "property").map do |item|
item.at("StreetAddress", "AlternativeStreetAddress").text
end
end
end
 
end
% ruby test.rb
Rehearsal -----------------------------------------
xpath   0.340000   0.000000   0.340000 (  0.336482)
css     0.620000   0.000000   0.620000 (  0.621865)
find    0.660000   0.000000   0.660000 (  0.655835)
-------------------------------- total: 1.620000sec

            user     system      total        real
xpath   0.320000   0.000000   0.320000 (  0.321618)
css     0.620000   0.000000   0.620000 (  0.621304)
find    0.650000   0.000000   0.650000 (  0.641275)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.