yCa*_*ran 13 c malloc optimization calloc
我饶有兴趣地阅读了malloc和calloc之间的后C差异.我在我的代码中使用了malloc,想知道我使用calloc会有什么不同.
我目前的(伪)代码与malloc:
场景1
int main()
{
allocate large arrays with malloc
INITIALIZE ALL ARRAY ELEMENTS TO ZERO
for loop //say 1000 times
do something and write results to arrays
end for loop
FREE ARRAYS with free command
} //end main
Run Code Online (Sandbox Code Playgroud)
如果我使用calloc而不是malloc,那么我将:
Scenario2
int main()
{
for loop //say 1000 times
ALLOCATION OF ARRAYS WITH CALLOC
do something and write results to arrays
FREE ARRAYS with free command
end for loop
} //end main
Run Code Online (Sandbox Code Playgroud)
我有三个问题:
如果阵列非常大,哪个场景更有效?
如果阵列非常大,哪个场景会更有时间效率?
在这两种情况下,我只是在编写数组,因为对于for循环中的任何给定迭代,我都是从第一个元素到最后一个元素顺序编写每个数组.重要的问题:如果我在场景1中使用malloc,那么我是否有必要将元素初始化为零?用malloc说我有数组z = [garbage1,garbage2,garbage 3].对于每次迭代,我按顺序编写元素,即在第一次迭代中我得到z = [some_result,garbage2,garbage3],在第二次迭代中我得到第一次迭代我得到z = [some_result,another_result,garbage3]等等在,然后我需要专门在malloc后初始化我的数组?
Rar*_*arr 11
假设在两个示例中初始化的内存总量是相同的,分配内存calloc()可能比分配内存更快malloc(),然后在单独的步骤中将它们归零,特别是如果malloc()您通过迭代单独归零元素在他们的循环中.A malloc()后跟一个memset()可能会快一样calloc().
如果在将实际存储计算结果之前不关心数组元素是垃圾,则不需要在之后实际初始化数组malloc().