Skip to content

Instantly share code, notes, and snippets.

@ph
Created April 16, 2015 20:55
Show Gist options
  • Save ph/f1d55e792e9cb3805d82 to your computer and use it in GitHub Desktop.
Save ph/f1d55e792e9cb3805d82 to your computer and use it in GitHub Desktop.
source "https://rubygems.org"
gem "benchmark-ips"
require "benchmark/ips"
class Java::JavaUtil::LinkedHashMap
# Java 8 Map implements a merge method with a different signature from
# the Ruby Hash#merge. see https://github.com/jruby/jruby/issues/1249
if ENV_JAVA['java.specification.version'] >= '1.8'
def merge_ruby(other)
# commented is a Java implementation, need to bench to see which is most efficient
# and if this implementation respects the Ruby merge contract.
#
dup.merge!(other)
end
def merge_java(other)
duped = Java::JavaUtil::LinkedHashMap.new(self)
duped.putAll(Java::JavaUtil::LinkedHashMap.new(other))
duped
end
def merge_java2(other)
duped = self.clone
duped.putAll(Java::JavaUtil::LinkedHashMap.new(other))
duped
end
end
end
m1 = { "hello" => "maximun", "World" => "bye", "nested2" => [1, 2, 3, 4], "array" => [1] }
m2 = { "World" => "Uncool", "nested" => { "complex" => "structure" }, "array" => [2,3] }
Benchmark.ips do |x|
x.warmup = 5
x.report("merge ruby") do
m = Java::JavaUtil::LinkedHashMap.new(m1)
m.merge_ruby(m2)
end
x.report("merge java") do
m = Java::JavaUtil::LinkedHashMap.new(m1)
m.merge_java(m2)
end
x.report("merge java 2") do
m = Java::JavaUtil::LinkedHashMap.new(m1)
m.merge_java2(m2)
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment