C - Is realloc'ing arrays to arrays twice the size efficient in dynamic data structures? -


lately i've been writing lot of code in c , i've noticed, thing takes time in programs resizing dynamic data structures. let's have array characters , want append characters end of array. way:

  1. check if there enough memory allocated.
  2. if not, realloc array array having twice size (using realloc)
  3. if there enough memory now, append characters, else go point 2.

i'm wondering if efficient enough. example think of tree structure hold arrays in nodes of tree, , way instead of copying old elements new array before appending something, add newly malloc'ed elements next node of tree , append characters there. way avoid unnecessary copying...

so that's 1 way of doing resizing differently. should else or solution of copying old elements new array twice size efficient enough?

as "most efficient" questions, way know measure actual performance in real-life conditions.

generally speaking, there can big performance gains having items in consecutive memory locations, that's cache-friendly layout algorithm that's processing items 1 after other. overall, consecutive array uses less space, well, because don't need space store additional data (like tree nodes).

while doubling size when need grow common approach, can tend eat address space. stl implementations grow structures vectors 1.5x instead of 2x avoid pathological cases. in short term, leads more allocations can lead less memory fragmentation. may or may not apply if you're using realloc. depends how realloc succeeds in doing in place.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -