Performance impact of realloc ()

前端 未结 4 2164
感情败类
感情败类 2021-02-18 15:41

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 reallo

4条回答
  •  情话喂你
    2021-02-18 16:10

    A realloc isn't really very expensive. But calling realloc for each element is a bit much. I suggest you do this:

    • Start with a size
    • When you add an element, check if you have enough space
    • When you don't have enough space, double the currrent amount

    Correctly guessing an adequate initial size also helps. So if 60% of your inputs are less than 100 records, start with that.

提交回复
热议问题