0

Let's say I know the max size of my new would be 8 but in most cases, the logical size would be lower given the program's logic. In this scenario, is it more memory and time efficient to?:

A. Begin with an array with a physical size of 1 and write to it and afterwards extend (dynamically allocate and freeing the old array) it by one each time and then continue writing to it.

B. Begin with an array of the given max size (in our case 8) and write every needed slot in this array and at the end shrink it to the logical size (dynamically allocated and freeing the old array).

EliranP1
  • 11
  • 2
  • Hint: `1+2+...+n = n(n+1)/2` – Damien Apr 21 '21 at 18:48
  • 6
    One common strategy is to double the allocated size each time extra space is needed. This way you avoid enlarging it every time. – Eugene Sh. Apr 21 '21 at 18:50
  • 3
    If you know the max size is 8, then create it at 8 and save many bytes of code. – stark Apr 21 '21 at 18:51
  • 6
    For 8 of course I wouldn't bother – Eugene Sh. Apr 21 '21 at 18:51
  • 3
    Is this a practical example? Are the elements of the array huge? I recommend trying to avoid dynamic allocation unless you really don't know much data you'll need until runtime, or you need "a lot" of memory. If your elements are small and you'll need a max of 8, just use automatic or static storage. Memory is cheap, who cares if a few bytes go unused? This will be faster (no overhead dynamically requesting memory) with less bookkeeping. This may be of some interest: https://stackoverflow.com/questions/8800482/when-and-why-to-use-malloc – yano Apr 21 '21 at 19:01
  • Yes, in my case I only need 8 spots maximum of a struct containing two chars, nothing major. Wanted to take the opportunity to know in general as well. Thanks for your comments, everyone. – EliranP1 Apr 21 '21 at 19:07
  • There is no silver bullet, it always depends on requirements (memory footprint, scope, life time, code size, run time, source maintainability, just to name some). Define your requirements, and some solutions are better than others. – the busybee Apr 21 '21 at 20:25
  • If those extra bytes are causing memory problems, because you have to allocate a lot of them, it might matter. If not, I would always allocate the max size and shinrk if needed. However for a small size, shrinking the memory may not have the desired result, as it could fragment your memory anway, causing a slowdown. It also depends how big those elements are. Generally I try to avoid dynamic allocations whereever I can as they are expensive. – Devolus Apr 21 '21 at 21:02

0 Answers0