Lately I've been writing a lot of code in C and I've noticed, that the thing that takes most time in my programs is resizing dynamic data structures. Let's say we have an array with characters and I want to append some characters to the end of this array. I do this that way:
- Check if there is enough memory allocated.
- If not, realloc array to array having twice the size (using realloc)
- If there is enough memory now, append the characters, else go to point 2.
I'm just wondering if this is efficient enough. For example I could think of something like a tree structure where I would hold the arrays in nodes of the tree, and that way instead of copying old elements to new array before appending something, I would just add newly malloc'ed elements to the next node of the tree and append the characters there. That way I would avoid unnecessary copying...
So that's just one way of doing that resizing differently. Should I look for something else or is my solution of just copying old elements to new array twice the size efficient enough?