Search code examples
c++constructorinitialization

Is the memory initialization/deletion so time-consuming?


I have small class Entity with some int fields and field that is two dimensional array of 50 ints. Nothing special.

I generate a lot (millions of such entities), each entity is differ: the array is differs and fields are differs. For my surprise I found that it is > 2x faster to not create each time new entity and just reuse existent and just set to 0 it fields and array. Is the memory initialization/deletion so time-consuming?


Solution

  • There is overhead associated with the memory management of objects. This can result in slowdowns.

    The best way to know is to time it, as you have done.
    Sometimes it won't bother you, other times, you will be very sensitive to it.

    Think about which loop would be faster:

    while (/* not done */) {
        Ask system for memory
        Create object
        Write into object
        Destroy object
    }
    

    or

    while (/* not done */) {
        Write into object
    }