Why new()/delete() is slower than malloc()/free()?
EDIT:
Thanks for the answers so far. Please kindly point out specifications of standard C++ implementation of new() and delete() if you have them thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Look at this piece of C code:
The
newoperator in C++ is essentially doing what the above piece of code does. That’s why it is slower thanmalloc().Likewise with
delete. It’s doing the equivalent of this:If the constructors and destructors are empty (like for built-ins),
newanddeleteshouldn’t be slower thanmalloc()andfree()are. (If they are, it’s often due to the fact that common implementations callmalloc()/free()under the hood, so they are a wrapper around them. Wrapping costs. Also, there might be code that needs to find out that no constructors/destructors are to be called. That would cost, too.)Edit To answer your additional question:
newanddeletearen’t functions, they are operators. This:new data()is called a new expression. It does two things. First it calls theoperator new, then it initializes the object, usually by invoking the appropriate constructor. (I say “usually” because built-ins don’t have constructors. But a new expression involving a built-in works the same nevertheless.)You can manipulate both of these phases. You can create your own constructors to manipulate initialization of your types and you can overload
operator new(even with several overloads having different additional arguments and also specifically for each class, if you want) in order to manipulate allocation of free storage. If you don’t implement your ownoperator new, the version from the standard library is used. A common implementation of this callsmalloc().Likewise, if you write
delete pd, called a delete expression, two things happen: depending onpd, the object is de-initialized, usually by calling its destructor, then the memory is released by calling the appropriateoperator delete.Again, you can manipulate both phase, by writing your own destructor, and by writing your own version of
operator delete. (The version ofoperator deletethat comes with your standard library is often implemented to callfree().)