java sting capacity method

Viewed 77

what is the real time use of JAVA StringBuffer.capacity() METHOD ...?
can anyone let me know the use case where it actually used for...?

class StringBufferExample6 {
    public static void main(String args[]) {
        StringBuffer sb = new StringBuffer();
        System.out.println(sb.capacity());// default 16
        sb.append("Hello");
        System.out.println(sb.capacity());// now 16
        sb.append("java is my favourite language");
        System.out.println(sb.capacity());// now (16*2)+2=34 i.e (oldcapacity*2)+2
    }
}

4 Answers

If you know that your StringBuffer is going to hold 10000 characters, it makes sense to set the initial capacity to 10000:

StringBuffer sb=new StringBuffer(10000);

This way the backing char array holding the data will not have to be re-allocated multiple times, which can improve performance.

If you know the possible number of characters beforehand. You can set the capacity, so the compiler will allocate that much memory. It helps in performance improvement as the compiler doesn't have to re-allocate the memory every time the StringBuffer is modified.

The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur (from docs).

Usually minimum is length + 16, when character count is exceeded the allocated amount, this stringbuffer also increases it size.

Related