none
Collection RRS feed

  • Question

  • As we know that collection can resizable by automatically,so when we add the value initially into collection collection class it will increase size by default 4 .

    So my question is that Why it increase the capacity to 4,what is the reason behind it ?

    2.If programmer initialize the value for some memory of allocated for collection then other memory space are wastage so is their any way to allocated the space for unused memory. For e.g a ArrayList is declared and when i added a value into the array list it automatically increase the size of Array List by 4 ,but i am only storing 1 value where as other memory space wastage so my question is their any way to allocate the unused memory by programmer to increase the efficiency of memory.


    S.K Nayak

    Thursday, July 24, 2014 12:35 PM

Answers

  • You're storing only one value now but later you may more values. If the capacity is increased only by 1 each time you add a value then the performance will go down the drain. Increasing the capacity requires a new array to be allocated and the contents of the old array be copied to the new array. That's not exactly efficient to do so it's preferable to increase the capacity by more than 1 when you use Add so this expensive work is not performed very often.

    List<T> (I don't care about ArrayList and you shouldn't care either, it's everything but obsolete) has a constructor which allows to specify the initial capacity. This constructor can be used in those cases where you have a lot of list objects with 1-3 elements. It can also be used when you know in advance the final count of the list or at least a reasonably good approximation of it.

    There's also TrimExcess which can be used to reduce overallocation in cases where you know that you won't be adding any more values to a list.

    Friday, July 25, 2014 8:04 AM
    Moderator