When compiled with optimization flag O3, function 2 is approximately 50-100 times faster than function 1 (tested on Ubuntu using time). Clearly, the new operator makes function1() slower. Is there any way one can reduce the overhead introduced due to frequent usage of new operator ?
Of course function 1 is slower. new, delete, new[], and delete[] are overloaded operators, and they have been overloaded with functions. Not only that, they are extra instructions. However, they allocate memory on the stack and not the heap. The second allocates on the heap, but isn't dynamic.Thanks Athar
It's possible to replace new with a custom version that adapts better to your particular usage pattern.
However, you should avoid new and delete when they're not necessary (like in function1), for a variety of reasons.
Not only that, they are extra instructions. However, they allocate memory on the stack and not the heap. The second allocates on the heap, but isn't dynamic.
But tell me seriously why would one want to do that and get down to all the hairy details of allocating memory? I would presume it will be needed depending on the business nature of the IT system. Most business-centric system can do just fine with the compiler provided implementation of the new operator.
Why would one want to write your own version of new? Here are three practical examples.
Suppose you have a linked list and you want to speed up the allocation of new nodes. One way to do this is to maintain a list of deleted nodes, whose memory can be reused when new nodes are allocated. Instead of using the default new and delete, new will be overloaded to try to get a node from the list of deleted nodes; only if no deleted nodes are available would it dynamically allocate memory. Delete will simply add the node to the deleted nodes. This way instead of allocating new memory from the heap (which is pretty time consuming) we will use the already allocated space. The technique is usually called caching.
Reimplementation of new/delete operators to provide garbage collection for your objects, so your objects will be deleted automatically when they are no longer used.
Creating an arena allocator that makes memory allocations and deallocations lightning fast at the cost of temporarily holding on to more memory than necessary by allocating a large block up front and then carving out one piece at a time.