Reputation: 521
I have a very simple piece of code which iterates over a list of Database objects and appends certain property to the StringBuilder. Now the results are sometimes going over 100K so the append operations go over 100K
My problem is there is no way I can shorten the number of iterations as I need the data. But Stringbuilder keeps on taking over heap space. And throws OutOfMemoryException.
Has anyone encountered any such situation and is there a solution to this problem or an alternative to StringBuilder.
It is quite possible that what I am doing might as well be wrong so even though code is quite simple I will post it.
StringBuilder endResult = new StringBuilder();
if (dbObjects != null && !dbObjects.isEmpty()) {
for (DBObject dBO : dbObjects) {
endResult.append("Starting to write" + dBO.getOutPut() + "content");
endResult.append(dBO.getResults);
}
output.append("END");
}
Like I said it's quite possible that I will have 100000 results from the DB
Upvotes: 5
Views: 5304
Reputation: 524
You shouldn't do something like this when using StringBuilder
:
endResult.append("Starting to write" + dBO.getOutPut() + "content");
The above statement will do string concatenation. Use the append()
method like:
endResult.append("Starting to write").append(dBO.getOutPut()).append("content");
Upvotes: 2