Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance impact of realloc ()

Tags:

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 ?

like image 930
vindyz Avatar asked Jul 17 '11 22:07

vindyz


People also ask

Is realloc costly?

A realloc isn't really very expensive. But calling realloc for each element is a bit much.

What is the time complexity of realloc?

If you take a look at the complexity, assuming realloc is O(N), you quickly conclude that adding a single byte is on average O(1), which is good.

Should I use realloc?

It's perfectly safe to use realloc . It is the way to reallocate memory in a C program. However you should always check the return value for an error condition.

Does realloc work with new?

Use of realloc() realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object is identical to that of the old object prior to deallocation, up to the lesser of the new and old sizes.


1 Answers

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.

like image 173
cnicutar Avatar answered Oct 15 '22 08:10

cnicutar