I have benchmarked 2 different ways to add an element in a map
container.
1 map.insert(key,val)
2 map[key]=val
I used gcc and it comes out that the second way is about twice as
fast as the first one.
Is there a reason/case why I should use the insert() method rather
the operator[]?
Are the 2 different completely equivalent?
No, they are not. According to the Standard, the second one creates
a default 'value' associated with 'key' in the container, and then uses
the assignment op to get the contents of 'val' into the newly created
value. The operator[] is said to be implemented in terms of 'insert'.
So, all things being standard, I'd expect 'insert' to work faster in
general.
Strange, here is my very simple (maybe too simple?) benchmark
#include <map>
#include <string>
#include <iostream>
#include <ctime>
typedef std::map<int, std::string> lut;
typedef lut::value_type pair;
#define BENCH(BLOCK,NAME,N) \
{ \
lut a; \
clock_t tic=clock(); \
for (int i=0; i<N; i++) { \
BLOCK \
} \
double elapsed = double(clock()-tic)/N/CLOCKS_PER_SEC; \
std::cout << "Time elapsed = " << 1e9*elapsed << " ns" << std::endl; \
} \
int const N=100000;
int main()
{
BENCH(a.insert(pair(i%1000,"foo1"));,"map::insert()",N)
BENCH(a[i%1000]="foo1";,"map:
perator[]",N)
BENCH(lut a; a.insert(pair(i%1000,"foo1"));,"map::insert()",N)
BENCH(lut a; a[i%1000]="foo1";,"map:
perator[]",N)
}
And the output on a linux box runnig g++ 3.2.3 compiling without any
optimisation
Time elapsed = 900 ns
Time elapsed = 500 ns
Time elapsed = 1100 ns
Time elapsed = 1200 ns
How do you explain this?