best way to allocate memory?
-
Are any of the following ways of allocating memory faster or more efficient than the others: malloc, calloc, free c++ new, delete LocalAlloc, LocalFree GlobalAlloc, GlobalFree CoTaskMemAlloc, CoTaskMemFree -thanks
-
Are any of the following ways of allocating memory faster or more efficient than the others: malloc, calloc, free c++ new, delete LocalAlloc, LocalFree GlobalAlloc, GlobalFree CoTaskMemAlloc, CoTaskMemFree -thanks
malloc and free are probably the fastest, given that in most heap managers, they are obtaining memory from a pool managed by the C runtime. calloc is inherently slower than malloc, since it calls malloc and then initializes the allocated memory to all zero's. new and delete are slower than malloc and free, since they allocate/deallocate memory and then call the constructor/destructor for the object. The remaining functions I would think would be slower than malloc/free/new/delete, since they involve Win32 API or COM calls. That said, I agree with the other poster. If you are using C++, you should use new and delete wherever possible. Most of the time, the first thing you do with allocated memory is initialize it. The C++ new operator couples the allocation and initialization together, making it more difficult to fail to initialize what your allocating.
Software Zen:
delete this;
-
Are any of the following ways of allocating memory faster or more efficient than the others: malloc, calloc, free c++ new, delete LocalAlloc, LocalFree GlobalAlloc, GlobalFree CoTaskMemAlloc, CoTaskMemFree -thanks
With the MS C/C++ library running on W2K etc then I think you'll find that all those end up at the API 'HeapAlloc'. So if you're really after most efficiency then consider going direct. In general though 'new'/'delete' for C++. And create your own allocators for special cases. For instance if you're allocating large numbers of small constant sized objects then a specialised allocator based on a number of larger allocations from the system is worth looking at. As in all optimisation the big win is to get the high level aspects of the program efficient before micro optimising. Say you make all your allocations run in 95% of the time, and I tweak my app to do half the number of allocations. Who's won? Who's kept their app maintainable and simple? Etc etc. Paul