0

Have a look at this piece of code:

class Profiler{
    const std::string id;
public:
    Profiler(const std::string id);
    Profiler(const Profiler &t);
//...
}

then somewhere in the code:

std::map<const std::string, Profiler> profilers;

and somewhere else I populate the container as:

profilers.insert(std::pair<const std::string, Profiler>(id, Profiler(id)));

The above line just invoked constructor and copy constructor 3 times in total. one for creating the temporary Profiler, one for creating a pair and one for insert right? profilers[id] = Profiler(id); also has same number of invocations.

  1. is there any way to reduce this number?
  2. isn't it cheaper(in any terms) to change the signatures properly to create a Profiler in the heap and store its address in the map ? (Profiler objects are small)

thanks

rahman
  • 4,370
  • 13
  • 42
  • 80
  • Better use a `std::set` with custom comparator instead. – Deduplicator Sep 11 '14 at 04:21
  • the `std::map` will store its actual data from the free-store (heap) by default. Only a small handle will occupy the stack. – Galik Sep 11 '14 at 04:29
  • 1
    If you have C++11 you can use `profilers.emplace()` to reduce copying. – Galik Sep 11 '14 at 04:30
  • 3
    Keep in mind that stack operations and data copying are typically much cheaper than heap allocations, so it may well be faster to do extra copy-constructors, etc: http://stackoverflow.com/questions/2264969/why-memory-allocation-on-heap-is-much-slower-than-on-stack – Jeremy Friesner Sep 11 '14 at 04:50

1 Answers1

0

I my situation, like in my other situation, stack is more preferrable. Why? better read them one:

  1. why memory allocation on heap is much slower than onstack
  2. which is faster stack allocation or heap allocation
Community
  • 1
  • 1
rahman
  • 4,370
  • 13
  • 42
  • 80