Skip to content

Instantly share code, notes, and snippets.

@colinsurprenant
Created April 17, 2015 11:41
Show Gist options
  • Save colinsurprenant/bc3575efde2743f14666 to your computer and use it in GitHub Desktop.
Save colinsurprenant/bc3575efde2743f14666 to your computer and use it in GitHub Desktop.
Java Collection union and intersection patches benchmarks
require "benchmark/ips"
module java::util::Collection
# support the Ruby intersection method on Java Collection
def i_1(other)
# transform self into a LinkedHashSet to remove duplicates and preserve order as defined by the Ruby Array intersection contract
duped = Java::JavaUtil::LinkedHashSet.new(self)
duped.retainAll(other)
duped
end
def i_2(other)
to_a & other
end
# support the Ruby union method on Java Collection
def u_1(other)
# transform self into a LinkedHashSet to remove duplicates and preserve order as defined by the Ruby Array union contract
duped = Java::JavaUtil::LinkedHashSet.new(self)
duped.addAll(other)
duped
end
def u_2(other)
to_a | other
end
end
m1 = ["foo1", "foo2", "foo3", "foo4", "foo5", "foo6", "foo7", "foo8", "foo9"]
m2 = ["foo5", "foo6", "foo7", "foo8", "foo9", "foo10", "foo11", "foo12", "foo13"]
Benchmark.ips do |x|
x.warmup = 30
x.time = 30
m = Java::JavaUtil::ArrayList.new(m1)
x.report("u_1 addAll") do
m.u_1(m2)
end
m = Java::JavaUtil::ArrayList.new(m1)
x.report("u_2 to_a") do
m.u_2(m2)
end
x.compare!
end
Benchmark.ips do |x|
x.warmup = 30
x.time = 30
m = Java::JavaUtil::ArrayList.new(m1)
x.report("i_1 retainAll") do
m.i_1(m2)
end
m = Java::JavaUtil::ArrayList.new(m1)
x.report("i_2 to_a") do
m.i_2(m2)
end
x.compare!
end
source "https://rubygems.org"
gem "benchmark-ips"
tested on MBP 13r, OSX 10.10.2, Java 8, JRuby 1.7.17
$ bundle exec ruby collection_benchmark.rb
Calculating -------------------------------------
u_1 addAll 26.113k i/100ms
u_2 to_a 16.348k i/100ms
-------------------------------------------------
u_1 addAll 311.945k (± 7.0%) i/s - 9.322M
u_2 to_a 194.675k (±18.8%) i/s - 5.591M
Comparison:
u_1 addAll: 311945.3 i/s
u_2 to_a: 194674.9 i/s - 1.60x slower
Calculating -------------------------------------
i_1 retainAll 28.592k i/100ms
i_2 to_a 18.481k i/100ms
-------------------------------------------------
i_1 retainAll 346.149k (± 6.1%) i/s - 10.350M
i_2 to_a 226.566k (±22.1%) i/s - 6.376M
Comparison:
i_1 retainAll: 346148.6 i/s
i_2 to_a: 226566.3 i/s - 1.53x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment