多个realloc的不是一个巨大的malloc更贵? [英] Are multiple realloc more expensive than a huge malloc?
问题描述
我使用的是动态数组重新present一分堆。有一个循环,去除最低和随机元素,直到某些条件发生添加到最小堆。虽然我不知道堆的长度如何在运行时改变(有一个很大的随机性),我知道了上限,即10万元。我有两个选择:
I am using a dynamic array to represent a min-heap. There is a loop that removes minimum, and add random elements to the min-heap until some condition occur. Although I don't know how the length of the heap will change during run-time (there is a lot of randomness), I know the upper bound, which is 10 million. I have two options:
1)使用malloc声明一小阵,那么当有堆元素的个数超过了长度打电话的realloc。
1) Declare a small array using malloc, then call realloc when there number of elements in the heap exceeds the length.
2)声明了1000万入境阵列使用malloc。这避免了以往任何时候都调用realloc的。
2) Declare a 10 million entry array using malloc. This avoids ever calling realloc.
问
时的选项2比方案1更有效?
Is option 2 more efficient than option 1?
我和我的code使用2。这是因为在code中的随机性测试估计这一点,似乎有显著(20%),运行时间减少。是否有任何缺点,宣布大10-50万元入门阵列使用malloc前面?
I tested this with my code and there seems to be significant (20%) run-time reduction from using 2. This is estimated because of the randomness in the code. Is there any drawback to declaring a large 10-50 million entry array with malloc up front?
推荐答案
如果您能抽出内存,使大量的前期配置,它提供了有价值的业绩增长,然后通过各种手段做到这一点。
If you can spare the memory to make the large up-front allocation, and it gives a worthwhile performance increase, then by all means do it.
如果您坚持使用的realloc
,那么你可能会发现,规模每增加了一倍,而不是一个固定的量增加可以提供性能和效率之间的良好权衡内存使用情况。
If you stick with realloc
, then you might find that doubling the size every time instead of increasing by a fixed amount can give a good trade-off between performance and efficient memory usage.
这篇关于多个realloc的不是一个巨大的malloc更贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!