Rule Definition
One of the fundamental OO performance management principles is this: Avoid excessive object creation. This doesn't mean that you should give up the benefits of object-oriented programming by not creating any objects, but you should be wary of object creation inside of tight loops when executing performance-critical code. Object creation is expensive enough that you should avoid unnecessarily creating temporary or intermediate objects in situations where performance is an issue.
Remediation
Redesign the loop.
Violation Code Sample
public class MyLoop {
public void printCount() {
for (int i = 0; i < 100; i++) {
StringBuffer sb = new StringBuffer(); // VIOLATION
sb.append("count = ");
sb.append(i);
System.out.println(sb);
}
}
}
Fixed Code Sample
public class MyLoop {
public void printCount() {
StringBuffer sb = new StringBuffer(); // FIXED
for (int i = 0; i < 100; i++) {
sb.setLength(0);
sb.append("count = ");
sb.append(i);
System.out.println(sb);
}
}
}
Related Technologies
Technical Criterion
Efficiency - Expensive Calls in Loops
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.