Re: malloc vs. realloc
From: Jack Klein (jackklein_at_spamcop.net)
Date: 11/25/03
- Next message: Vijay Kumar R Zanvar: "Re: loop will not stop!!!"
- Previous message: nobody: "Re: malloc vs. realloc"
- In reply to: Pushkar Pradhan: "malloc vs. realloc"
- Next in thread: Dan Pop: "Re: malloc vs. realloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 25 Nov 2003 04:48:44 GMT
On Mon, 24 Nov 2003 22:06:19 -0600, Pushkar Pradhan
<pushkar@gri.msstate.edu> wrote in comp.lang.c:
> I've a code in which I don't know how many elements an array may
> contain, BUT I know the max. no. of values it may have. So I do this
> malloc(MAXLEN), however I can use realloc(...) each time I add a new
> element to this array.
>
> Now my question is: will doing realloc everytime slow down the code very
> much? My project is concerned about high performance.
> Pushkar Pradhan
The C standard does not specify performance of anything. Much depends
on your particular compiler and operating system, which you can either
test or ask about in a group that supports your system.
There is a good chance that at least some reallocation calls will be
expensive in terms of time. Perhaps a better memory allocation
strategy would be in order.
If you really need to shrink the memory block, is it possible that you
can do it after all elements are added, instead of after each one?
If that is not possible, you could start out with an allocation for
some fraction of the maximum size, for example 25%. If you used that
up you could allocate another 25%, and another and another.
Other possibilities are to pick some likely size and always double it
or multiply it by 1.5 each time you need to grow the block.
You should investigate the typical needs of the program, if possible.
The maximum number of elements might be 1000, but perhaps most of the
time it will need 100 or less.
-- Jack Klein Home: http://JK-Technology.Com FAQs for comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html comp.lang.c++ http://www.parashift.com/c++-faq-lite/ alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
- Next message: Vijay Kumar R Zanvar: "Re: loop will not stop!!!"
- Previous message: nobody: "Re: malloc vs. realloc"
- In reply to: Pushkar Pradhan: "malloc vs. realloc"
- Next in thread: Dan Pop: "Re: malloc vs. realloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|