3 ms·
> the efficiency gains of new/delete over malloc/free are going to become apparent. What are those?
by loeg 5y ago
> the efficiency gains of new/delete over malloc/free are going to become apparent.
What are those?
- jeffbee 5y agonew, when the compiler can see the definition at build time and with known size, may compile down to as little as two x86 instructions without a call. That's not generally true of malloc. C also lacks an equivalent of sized delete, which is very efficient. In C the implementation of free has to figure out what size ptr represented.
- remexre 5y agoIs that some sort of allocation elision where it's actually on the stack? Or more to the point, what are those two instructions?
- mariusor 5y ago> new, [...] may compile down to as little as two x86 instructions Yes, but when you have a million of allocation, that still means two million instructions. malloc/free allows a much easier path to allocating a large chunk of memory in which you can play around with your million structs having only the overhead of accessing pointers (and, of course, thinking about where to point them).
- kaba0 5y agoWith all due respect, that is trivial to do in C++, hell it will be actually readable and much safer than malloc(n*sizeof(something)) and then for looping over that to initialize values.
- maximilianburke 5y agoI mean, there shouldn't be any, given how many C++ standard libraries implement `operator new` on top of malloc. If anything it should be less efficient once you factor in constructor calls. libc++: https://github.com/llvm-mirror/libcxx/blob/master/src/new.cpp https://github.com/llvm-mirror/libcxx/blob/master/src/new.cp... libstdc++: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/new_op.cc https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-...
- jeffbee 5y agoIt is common in C++ to override operators new and delete. When you use tcmalloc in a C++ program it overrides all the global allocator and deallocator operators. When you use tcmalloc in a C program, it just overrides malloc, because there is no richer API available.
- maximilianburke 5y agoAnd the same overriding can be done in a C program with malloc and free, too.