× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

String concatenation in a loop is bad.

suresh atta
Dec 22, 2015
<p>Consider the below code </p> <p> </p> <p> </p> <pre><code>for (int i = 0; i &lt; millionTimes; i++){ string += anystring ... } </code></pre> <p>IF you see the above code, you are creating million objects for no reason as string concatination creating an object internally.</p> <p> </p> <p>Always go for StringBuilder.</p> <pre><code><span style="color:rgb(43, 145, 175)">StringBuilder</span><span style="color:rgb(0, 0, 0)"> sb </span><span style="color:rgb(0, 0, 0)">=</span><span style="color:rgb(0, 0, 0)"> </span><span style="color:rgb(0, 0, 139)">new</span><span style="color:rgb(0, 0, 0)"> </span><span style="color:rgb(43, 145, 175)">StringBuilder</span><span style="color:rgb(0, 0, 0)">();</span></code></pre> <pre> <code><span style="color:rgb(0, 0, 139)">for</span><span style="color:rgb(0, 0, 0)">(</span><span style="color:rgb(0, 0, 0)"> </span><span style="color:rgb(0, 0, 139)">int</span><span style="color:rgb(0, 0, 0)"> i </span><span style="color:rgb(0, 0, 0)">=</span><span style="color:rgb(0, 0, 0)"> </span><span style="color:rgb(128, 0, 0)">0</span><span style="color:rgb(0, 0, 0)">;</span><span style="color:rgb(0, 0, 0)"> i </span><span style="color:rgb(0, 0, 0)">&lt;</span><span style="color:rgb(0, 0, 0)"> </span>millionTimes<span style="color:rgb(0, 0, 0)">;</span><span style="color:rgb(0, 0, 0)"> i</span><span style="color:rgb(0, 0, 0)">++</span><span style="color:rgb(0, 0, 0)"> </span><span style="color:rgb(0, 0, 0)">)</span><span style="color:rgb(0, 0, 0)"> </span><span style="color:rgb(0, 0, 0)">{</span><span style="color:rgb(0, 0, 0)"> sb</span><span style="color:rgb(0, 0, 0)">.</span><span style="color:rgb(0, 0, 0)">append</span><span style="color:rgb(0, 0, 0)">(</span><span style="color:rgb(0, 0, 0)"> </span><span style="color:rgb(128, 0, 0)">"someString"</span><span style="color:rgb(0, 0, 0)"> </span><span style="color:rgb(0, 0, 0)">); }</span></code></pre>
comments powered by Disqus