realloc对性能的影响() [英] Performance impact of realloc ()
问题描述
我有一个记录列表,一开始我不知道记录数。我需要将它们读入数组。
,因此建议一一阅读所有记录。一一重新分配&继续随着元素的出现而增加数组的大小,或者我应该花一遍时间来确定记录数吗? malloc只做一次吗?哪一个将在计算上更便宜?
I have a list of records, at the starting I dont know the number of records. I need to read them into array. so is it advisable to read all record one by one & doing realloc one by one & go on increasing the array size as the element comes OR should I spend one pass in identifying the number of records & do malloc only once ? Which one will be be less computationally expensive ?
推荐答案
A realloc
不是真的不是很贵。但是为每个元素调用 realloc
有点多。我建议您这样做:
A realloc
isn't really very expensive. But calling realloc
for each element is a bit much. I suggest you do this:
- 以大小开头
- 添加元素时,请选中如果您有足够的空间
- 当您没有足够的空间时,将当前金额加倍
正确猜测适当的初始大小也有帮助。因此,如果60%的输入少于100条记录,则从此开始。
Correctly guessing an adequate initial size also helps. So if 60% of your inputs are less than 100 records, start with that.
这篇关于realloc对性能的影响()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!