Optimizing a financial analysis application
As a Java developer for a financial analysis application, you've identified that one of your report-generation methods is creating excessive garbage and triggering frequent garbage collections. The report concatenates thousands of data points into a single string. You need to refactor this code to be more GC-friendly while maintaining the same functionality.
This exercise is part of the course
Optimizing Code in Java
Exercise instructions
- Create a new
StringBuilder
instance of the necessary length. - For every value in
dataPoints
, add the formatted value in the string builder. - Convert the
StringBuilder
to aString
and return it.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
public class Main {
public static String generateReportWithoutOptimization(double[] dataPoints) {
String report = "";
for (double value : dataPoints) {
report += String.format("%.2f, ", value);
}
return report;
}
public static String generateReportWithOptimization(double[] dataPoints) {
// Create a new string builder
StringBuilder report = ____(dataPoints.length * 8);
for (double value : dataPoints) {
// For every value, add the formatted value to the string builder
report.____(String.format("%.2f, ", value));
}
// Convert to string before returning
return report.____;
}
public static void main(String[] args) {
double[] testData = new double[10000];
for (int i = 0; i < testData.length; i++) {
testData[i] = Math.random() * 100;
}
long startWithoutOptimization = System.nanoTime();
String reportWithoutOptimization = generateReportWithoutOptimization(testData);
long endWithoutOptimization = System.nanoTime();
long startWithOptimization = System.nanoTime();
String reportWithOptimization = generateReportWithOptimization(testData);
long endWithOptimization = System.nanoTime();
System.out.println("Time taken without optimization: " + (endWithoutOptimization - startWithoutOptimization) / 1_000_000 + " ms");
System.out.println("Time taken with optimization: " + (endWithOptimization - startWithOptimization) / 1_000_000 + " ms");
}
}