UPDATE: I tested by concatenating with the +
operator and the performance was almost the same as by doing it with a StringBuilder (results in the end). This suggests, as some of you have mentioned in the answers, that the slower performance is due to the format analysis.
Conclusion: Java's printf() is not a efficient method for concatenating and printing strings. Either the +
operator or preferably a StringBuilder
should be used for better performance.
Does Java's printf()
use slow concatenation when creating Strings? i.e. does it create a new String after appending each element to the final String?
I tested using a StringBuilder
to create the string I obtained a performance improvement of about 4 times faster run time. This part of the program was called thousands of times in my program.
The only differences between the two tests were the following blocks of code:
1) printf()
(0.8 seconds):
System.out.printf("%d %d %d %d %d %d\n", nums[a], nums[b],
nums[c], nums[d], nums[e], nums[f]);
2) StringBuilder
+ println()
(0.2 seconds):
StringBuilder sb = new StringBuilder();
sb.append(nums[a]);
sb.append(' ');
sb.append(nums[b]);
sb.append(' ');
sb.append(nums[c]);
sb.append(' ');
sb.append(nums[d]);
sb.append(' ');
sb.append(nums[e]);
sb.append(' ');
sb.append(nums[f]);
System.out.println(sb.toString());
3) +
operaror + println()
(0.22 seconds):
System.out.println(nums[a] + " " + nums[b] + " " + nums[c] + " " + nums[d] + " "
+ nums[e] + " " + nums[f]);