Skip to content

Instantly share code, notes, and snippets.

@Papierkorb
Last active November 20, 2015 16:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Papierkorb/ab7bd6c5fdce12e3fc6c to your computer and use it in GitHub Desktop.
Save Papierkorb/ab7bd6c5fdce12e3fc6c to your computer and use it in GitHub Desktop.
MRI vs JRuby vs JRuby+Java
require 'benchmark'
require 'set'
range = (1..10_000)
subs = {}
clients = (1..5_000).to_a
chosen = clients.sample 50
# NOTE: Hash was added *after* I wrote the OP on Reddit.
puts "#{RUBY_ENGINE} #{RUBY_VERSION} #{RUBY_PLATFORM}"
[ Array, SortedSet, Hash ].each do |klass|
clients_per = 500 # 10%
if klass == Hash
10_000.times{|i| subs["foo:#{i}"] = clients.sample(clients_per).map{|a| [ a, nil ]}.to_h}
else
10_000.times{|i| subs["foo:#{i}"] = klass.new clients.sample(clients_per)}
end
r = Benchmark.measure do
subs.each do |_, cur|
chosen.each{|c| cur.delete c}
end
end
puts klass.name, r
end
require 'benchmark'
$CLASSPATH << 'java'
java_import 'foo.SubscriptionManager'
subs = SubscriptionManager.new
clients = (1..5_000).to_a
chosen = clients.sample 50
puts "#{RUBY_ENGINE} #{RUBY_VERSION} #{RUBY_PLATFORM}"
clients_per = 500 # 10%
10_000.times{|i| clients.sample(clients_per).each{|c| subs.add_subscription "foo:#{i}", c} }
r = Benchmark.measure do
chosen.each{|c| subs.remove_subscriptions_for_user c}
end
puts r
// After cloning/copying, run the following commands from the project directory to set it up:
// $ mkdir -p java/foo
// $ mv SubscriptionManager.java java/foo
// $ cd java/foo
// $ javac SubscriptionManager.java
// $ cd ../..
// You can now run the benchmarks yourself.
package foo;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import java.util.SortedSet;
class SubscriptionManager {
private Map<String, SortedSet<Integer>> subscriptions;
public SubscriptionManager() {
this.subscriptions = new HashMap<String, SortedSet<Integer>>();
}
public SortedSet<Integer> addOrGet(String name) {
SortedSet<Integer> set = this.subscriptions.get(name);
if (set == null) {
set = new TreeSet<Integer>();
this.subscriptions.put(name, set);
}
return set;
}
public void addSubscription(String name, Integer user) {
addOrGet(name).add(user);
}
public void removeSubscriptionsForUser(Integer user) {
for (Map.Entry<String, SortedSet<Integer>> entry : this.subscriptions.entrySet()) {
entry.getValue().remove(user);
}
}
public Map<String, SortedSet<Integer>> subscriptions() {
return this.subscriptions;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment