As it seems, placement new creates a new object on a preallocated memory, so does it mean that it would take less time? Looks like it’s faster then allocating using the old ordinary new. Then, if this is so convenient and faster, why not use placement new all the time?
As it seems, placement new creates a new object on a preallocated memory, so
Share
the normal (nonplacement)
newis basically equivalent to doingOf course the reality looks a bit different due to errorchecking and such, but the result is more or less the same (through not identical, you can’t
deletea pointer allocated that way, instead you need to call the destructor explicitely (ptr->~T()) and then release the memory usingfree).So placement new should indeed be faster then non placement new, since it doesn’t need to allocate the memory. However the problem is that the memory needs to be allocated somewhere. So you have essentially replaced one call to
newwith a call toplacement newand some code for the allocation somewhere (if not why would you usenewin the first place?). It should be obvious that this is less convinient and more bug prone.Now of course you can write a faster allocation method, but for that you typically need to do some sort of tradeoff. It’s not going to be easy to write a allocator which is faster without either using more memory (extra data for faster identification of free blocks) or making it very specific (writing fast allocation of a single objectsize is much easier then a general one). In the end it is typically not worth the effort (for scenarious where it is worth the effort it has likely already been done, so you could use an existing allocator (which likely uses placement new internally)).
There are of course uses for placement new (sometimes you do have the memory preallocated), but that is simply not the common case