Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is Capacity property of Stringbuilder really matters when we set its length to zero?

i see this Question

best-way-to-clear-contents-of-nets-stringbuilder/

the answerers set the length to zero and also worries about capacity ? does it really matter to set capacity ?

f we dis-assemble .net 4.5 Library , navigate to System.Text.StringBuilder

       /// <summary>
        /// Removes all characters from the current
 <see cref="T:System.Text.StringBuilder"/> instance.
        /// </summary>
        /// 
        /// <returns>
        /// An object whose <see cref="P:System.Text.StringBuilder.Length"/> 
        ///    is 0 (zero).

  /// </returns>
    [__DynamicallyInvokable]
    public StringBuilder Clear()
    {
      this.Length = 0;
      return this;
    }

is it really matters to set capacity when we already set its length to zero... or ms doesn't care that?

like image 502
Vishal Sharma Avatar asked Jan 03 '14 09:01

Vishal Sharma


1 Answers

No. It does not matter in every day code. Note that the stack you have linked to specifically addresses ditching that method in favour of the .net 4 implementation.

The Capacity of a StringBuilder dictates the initial size of the underlying buffer. This buffer will expand as needed - I think it simply doubles in capacity each time it needs to grow.

StringBuilder.Length keeps track of how much of the buffer is valid (assigned) data. Capacity and Length are independent.

Capacity is an optimization feature. By zeroing the capacity, all you are doing is ensuring that a memory allocation will have to be performed if you add characters to the StringBuilder in exchange for reclaiming that buffer straight away. It is a classic tradeoff.

Rarely do you need to complicated your code by modifying the capacity.

like image 111
Gusdor Avatar answered Oct 11 '22 22:10

Gusdor