且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C语言循环中的内存分配成本

更新时间:2022-05-02 05:06:17

内存分配的成本不是很依赖分配的大小。粗略地说,任何大小的内存分配都是O(1),显然标准库已经过优化,以使分配尽可能快。

The cost of a memory allocation is not very dependent on the size of the allocation. Roughly speaking, a memory allocation of any size is O(1), and obviously standard libraries are optimized to make allocations as fast as possible.

因此,如果您需要非常大的分配,例如在示例程序中,与初始化分配的内存的成本相比,分配的成本将是微不足道的(更不用说了)实际执行计算所需的费用)。

So if you need a very big allocation, as in the example program, the cost of allocation will be trivial compared with the cost of initializing the allocated memory (to say nothing of the cost of actually doing the computation which is required).

对于非常紧密的循环中的小分配,分配开销可能很明显,替代机制可能会有用;其中之一是问题中建议的一个,将预分配的数组作为附加参数传递给函数。 (其他可能性包括使用C的可变长度数组(VLA)(如果它们在所有目标平台上都可用)或 alloca / _alloca / _malloca 。)

For small allocations in very tight loops, where the allocation overhead might be noticeable, alternative mechanisms might be useful; one of these is the one suggested in the question, passing a preallocated array as an additional parameter to the function. (Other possibilities include using C's variable length arrays (VLAs), if they are available on all target platforms, or alloca/_alloca/_malloca.)

但我建议除非有确凿的证据表明不对这种形式进行微优化节省时间是合理的;否则,可维护性和可读性的成本将超过您可能节省的任何时间。

But I would suggest not implementing microoptimizations of this form until there is solid evidence that the time savings are justified; otherwise, the cost in maintainability and readability will outweigh any small time savings you might achieve.