Skip to content

Instantly share code, notes, and snippets.

@dspezia
Created April 27, 2012 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dspezia/2513690 to your computer and use it in GitHub Desktop.
Save dspezia/2513690 to your computer and use it in GitHub Desktop.
Mysterious Java performance
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>
#include <memory>
using namespace std;
int main()
{
unordered_set<long> s;
for ( long i=0; i<25000; ++i )
s.insert(i);
typedef pair<long,double> Object;
typedef shared_ptr<Object> Ptr;
unordered_map<long, Ptr > z1;
multimap<double, Ptr > z2;
for ( long i=0; i<25000; ++i ) {
Ptr p( new Object(i,double(i)) );
z1.insert( make_pair(i,p ));
z2.insert( make_pair(double(i),p ));
}
for ( int n=0; n<1000; ++n )
{
unordered_map<long,Ptr> r1;
multimap<double, Ptr> r2;
for ( auto i=z1.begin(); i != z1.end(); ++i )
if ( s.find( i->first ) != s.end() )
{
r1.insert( *i );
r2.insert( make_pair(i->second->second, i->second ));
}
}
return 0;
}
import java.util.*;
class Obj {
public long val;
public double score;
public Obj( long v, double s ) { val = v; score = s; }
}
class Test {
public static void main(String[] args) {
HashSet<Long> s = new HashSet<Long>();
for ( long i=0; i<25000; ++i )
s.add(i);
HashMap<Long,Obj> z1 = new HashMap<Long,Obj>();
TreeMap<Double,Obj> z2 = new TreeMap<Double,Obj>();
for ( long i=0; i<25000; ++i ) {
Obj p = new Obj( i, i );
z1.put( i, p );
z2.put( (double) i, p );
}
for ( int n=0; n<1000; ++n )
{
loop(s,z1,z2);
}
System.gc();
}
public static void loop( HashSet<Long> s, HashMap<Long,Obj> z1, TreeMap<Double,Obj> z2 )
{
long count = 0;
HashMap<Long,Obj> r1 = new HashMap<Long,Obj>();
TreeMap<Double,Obj> r2 = new TreeMap<Double,Obj>();
for ( Map.Entry<Long,Obj> x : z1.entrySet() )
{
if ( s.contains( x.getKey() ) )
{
r1.put( x.getKey(), x.getValue() );
r2.put( x.getValue().score, x.getValue() );
}
}
count += r1.size() + r2.size();
}
}
$ g++ --version
g++ (SUSE Linux) 4.5.0 20100604 [gcc-4_5-branch revision 160292]
$ g++ -std=c++0x -O2 main.cc
$ time ./a.out
real 0m33.838s
user 0m30.784s
sys 0m2.930s
$ java -version
java version "1.6.0_22"
$ javac main.java
$ time java Test
real 0m17.783s
user 0m17.853s
sys 0m0.318s
WTF?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment