In the following code
for (UserSelection userSelection : filterList) {
String filterName = checkForDataHolder(userSelection
.getCriteriaName());
csvRow.append(filterName + ":");
List<String> list = userSelection.getCriteriaValues();
String filterval = "";
csvRow.append(DATA_DELIMITER);
for (String value : list) {
filterval += checkForDataHolder(value) + ", ";
}
if (filterval.indexOf(",") != -1) {
filterval = filterval.substring(0, filterval
.lastIndexOf(","));
}
csvRow.append(DATA_HOLDER + filterval + DATA_HOLDER);
csvRow.append(NEW_LINE);
}
This line filterval += checkForDataHolder(value) + ", ";
causes Concatenation of strings within a loop which creates a StringBuffer for each concatenation. When placed in a loop, this can result in the creation and collection of large numbers of temporary objects. How do I create a StringBuffer before entering the loop, and append to it within the loop ?
Also in the following code
final StringBuffer csvRow = new StringBuffer();
csvRow.append(NEW_LINE);
csvRow.append(" ");
I want to Replace the string literal with a character literal to improve performance
consider the following code
public void writeHeader(List<String> headerColList) throws IOException {
this.header = headerColList;
String val;
try {
final StringBuffer csvRow = new StringBuffer();
for (int i = 0; i < header.size(); i++) {
if (i > 0) {
csvRow.append(DATA_DELIMITER);
}
val = checkForDataHolder(headerColList.get((i)));
if (!StringUtil.isEmpty(val)) {
csvRow.append(DATA_HOLDER + val + DATA_HOLDER);
}
}
if(!isHeaderProcessed) {
if(this.header != null) {
writer.write(csvRow.toString());
writer.write(NEW_LINE);
}
isHeaderProcessed = true;
}
} catch (Exception e) {
log.error(e);
}
}
I want to consider catching a more specific class of exception (one or more subclasses of Exception).which is the best option here ?