Skip to content

Instantly share code, notes, and snippets.

@sam
Created August 29, 2012 20:41
Show Gist options
  • Save sam/3518649 to your computer and use it in GitHub Desktop.
Save sam/3518649 to your computer and use it in GitHub Desktop.
ActiveSupport HashWithIndifferentAccess vs Java HashMap performance
#!/usr/bin/env jruby
require "rubygems"
require "active_support/hash_with_indifferent_access"
require "java"
require "benchmark"
SYMBOLS = []
STRINGS = []
GET_REPEAT = 100
puts "Preparing keys..."
1_000_000.times do |i|
i_s = i.to_s
STRINGS << i_s
SYMBOLS << i_s.to_sym
end
def bench(reporter, name, h)
reporter.report("#{name} set Symbol") do
SYMBOLS.each_with_index do |e,i|
h[e] = i
end
end
reporter.report("#{name} get String") do
GET_REPEAT.times do
STRINGS.each do |e|
h[e]
end
end
end
reporter.report("#{name} get Symbol") do
GET_REPEAT.times do
SYMBOLS.each do |e|
h[e]
end
end
end
end
Benchmark::bmbm do |x|
bench x, "HWIA", HashWithIndifferentAccess.new
bench x, "HashMap", java.util.HashMap.new
end
Preparing keys...
Rehearsal ------------------------------------------------------
HWIA set Symbol 4.480000 0.090000 4.570000 ( 3.423000)
HWIA get String 70.870000 0.420000 71.290000 ( 67.325000)
HWIA get Symbol 165.900000 0.530000 166.430000 (166.823000)
HashMap set Symbol 0.890000 0.050000 0.940000 ( 0.709000)
HashMap get String 53.500000 0.280000 53.780000 ( 52.815000)
HashMap get Symbol 24.830000 0.100000 24.930000 ( 24.955000)
------------------------------------------- total: 321.940000sec
user system total real
HWIA set Symbol 1.490000 0.030000 1.520000 ( 1.347000)
HWIA get String 58.700000 0.190000 58.890000 ( 59.274000)
HWIA get Symbol 157.110000 0.460000 157.570000 (158.355000)
HashMap set Symbol 0.250000 0.000000 0.250000 ( 0.257000)
HashMap get String 54.910000 0.230000 55.140000 ( 54.216000)
HashMap get Symbol 26.190000 0.090000 26.280000 ( 26.082000)
@sam
Copy link
Author

sam commented Aug 29, 2012

NOTE: I tried setting both Symbols and Strings initially as well. There was no significant different difference with HWIA after rehearsal with a large enough set. HashMap generally had a 30%-50% advantage with Symbols.

Neither made any difference to the get performance (as you would expect).

@sam
Copy link
Author

sam commented Aug 30, 2012

To summarize, getting a String from a HashMap was consistently slightly faster than HWIA. Insertion to a HashMap is several times faster (consistently). Getting a Symbol from a HashMap is also several times faster.

Keep in mind this is all through Ruby. If you have a mixed-language project, where the Java side accessing a shared HashMap wouldn't be generating wrapping JRuby::RubyObject wrappers, and performing coercion for every K/V I'd expect the difference to be much greater.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment