Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Allocate memory ahead or on every demand?

Tags:

c

I've got a simple (propably) question for you. When creating own dynamic array implementation in C, is it better to allocate memory ahead(let's presume, for 10 elements) when an array is close to reach its current maximum capability, or to realloc memory every time when element count changes?

I mean: for performance, elegance or whatever comes to your mind.

like image 910
shazarre Avatar asked Dec 14 '22 00:12

shazarre


2 Answers

The usual choice is to multiple the current size by a fixed number greater than one (1.5ish is common, as is 2) which gets you amortized O(n) total allocation and copying costs.

Note that there is no guarantee that you can increase the size of the array in place, so you may have to copy all the existing elements to the new location (realloc() does this automatically for you, but you still have to pay the cost).

like image 170
dmckee --- ex-moderator kitten Avatar answered Dec 24 '22 18:12

dmckee --- ex-moderator kitten


It's much better for performance to realloc as few times as possible. So you can do something like:

array = realloc(array, old_size * 2);

like image 22
Thomas Bonini Avatar answered Dec 24 '22 20:12

Thomas Bonini