C语言循环中的内存分配成本 [英] The cost of memory allocation in a loop in C

查看:98
本文介绍了C语言循环中的内存分配成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就时间而言,在循环内还是循环外分配数组是否有显着差异?

Is there a significant difference between allocating an array inside or outside a loop in terms of cost of time?

我在循环内的函数中使用了许多数组程序中,尽管会降低可读性,但我应该将所有数组作为函数参数传递以提高性能吗?例如:

I use many arrays in functions inside a loop in my program, should I pass all the arrays as function parameters to increase the performance although it decreases the readability? For example:

#include <stdlib.h>
#define N 1000000
void foo()
{
    int* array = (int*)malloc(N*sizeof(int));
    /*
    Do something with the array
    */
    free(array);
}
int main()
{
    int i;
    for(i=0; i<1000000; i++)
        foo();
    return 0;
}

#include <stdlib.h>
#define N 1000000
void foo(int* array)
{
    /*
    Do something with the array
    */
}
int main()
{
    int i;
    int* array = (int*)malloc(N*sizeof(int));
    for(i=0; i<1000000; i++)
        foo(array);
    free(array);
    return 0;
}


推荐答案

内存分配的成本不是很依赖分配的大小。粗略地说,任何大小的内存分配都是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.

这篇关于C语言循环中的内存分配成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆