diff options
author | Andrew Gallasch <andrewgallasch@gmail.com> | 2016-10-27 23:47:46 +1030 |
---|---|---|
committer | GitHub <noreply@github.com> | 2016-10-27 23:47:46 +1030 |
commit | 1b59bd1097b73f216a13c1e24fdab877261f7dd6 (patch) | |
tree | 05458086d2eccaf2124db1fce0dab681fcf8367a /java.html.markdown | |
parent | 70617f16c4cf8cf77b366346abe62279d23a5d82 (diff) | |
parent | bb504b97ca06322cc131105647943f0140d6e313 (diff) |
Merge pull request #2522 from adambard/string-builder-loops
Add StringBuilder usage tip
Diffstat (limited to 'java.html.markdown')
-rw-r--r-- | java.html.markdown | 15 |
1 files changed, 14 insertions, 1 deletions
diff --git a/java.html.markdown b/java.html.markdown index 13c75ffe..4fdd06cc 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -198,7 +198,20 @@ public class LearnJava { builderConcatenated.append("the StringBuilder class."); System.out.println(builderConcatenated.toString()); // only now is the string built // Output: You can use the StringBuilder class. - + + // StringBuilder is efficient when the fully constructed String is not required until the end of some processing. + StringBuilder stringBuilder = new StringBuilder(); + String inefficientString = ""; + for(int i = 0 ; i < 10; i++){ + stringBuilder.append(i).append(" "); + inefficientString += i + " "; + } + System.out.println(inefficientString); + System.out.println(stringBuilder.toString()); + // inefficientString requires a lot more work to produce, as it generates a String on every loop iteration. + // Simple concatenation with + is compiled to a StringBuilder and toString() + // Avoid string concatenation in loops. + // #3 - with String formatter // Another alternative way to create strings. Fast and readable. String.format("%s may prefer %s.", "Or you", "String.format()"); |