pablo
pablo

Reputation: 6402

C# Hashtable vs c++ hash_map

I'm comparing the following code in C++ and C# and C# (Mono 2.4) seems to be faster. Is there anything wrong with the C++ code?

 #include <map>
 #include <string>
 #include <iostream>
 #include <ext/hash_map>
 #include <boost/any.hpp>

 int main()
 {
    //std::map<long, long> m;
    // hash_map is a little bit faster
    __gnu_cxx::hash_map<long, long> m;

    for( long i = 0; i < 1000000; ++i )
    {
        m[i]  = i;
    }

 }

And C#

 using System;
 using System.Collections;

 public int Main()
 {
     Hashtable m = new Hashtable();

     for( long i = 0; i < 1000000; ++i )
     {
        m[i]  = i;
     }

}

C# code is actually twice as fast on the same machine.

$ time ./a.out

real    0m1.028s
user    0m0.986s
sys     0m0.041s

$ time mono test.exe

real    0m0.603s
user    0m0.732s
sys     0m0.090s

Upvotes: 0

Views: 1757

Answers (2)

Crashworks
Crashworks

Reputation: 41404

You need to compile the C++ code with compiler optimizations turned on for a fair comparison. Otherwise, you are comparing apples to debug builds — the compiler will not even try to emit fast code.

In GCC this would be the -O3 flag, to start with.

Upvotes: 8

csl
csl

Reputation: 11358

Some thoughts:

  • You're comparing Mono against Boost
  • Which optimization (default or not) settings did you use for Mono and C++ ?
  • What are the initial / default hash table sizes for the C# and C++ versions ?
  • Have you tried comparing against other C++ hash maps, such as the sparse hash table ?
  • Remember not only to look at real time, but actual CPU time used.

Upvotes: 4

Related Questions