Sunday, June 12, 2011

Insufficient memory problem with StringBuffer

Using string buffer without selecting the proper construction can lead to memory leak.

Lets have a look of the constructor of string buffer

Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
public StringBuffer() {
  super(16);
}


Suppose you are creating objects of type StringBuffer in a loop, no of objects may change depnding upon the input. Every time it will create object to store at least 16 characters, you may not need all the 16, in that case remaining space will be unused and cannout be allocated for other purpose.

At some point these unused memory location may lead to Out of memory problem.

Instead of that we can use another constructor

Constructs a string buffer with no characters in it and the specified initial capacity.
public StringBuffer(int capacity) {
  super(capacity);
}

No comments:

Post a Comment

Chitika