• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 156
  • Last Modified:

append things to String ...

Hello experts,

  I have a loop like:

  String myString = " ";
  for(int i=0; i<N; i++){
   myString += (String)i*10000; }

 the code becomes slower and slower when N gets larger ...
 is there any other better way (faster ways) to append things the the String ?

2 Solutions
Use StringBuffer or StringBuilder instead

  StringBuffer buffer = new StringBuffer(N*5);
  for(int i=0; i<N; i++){
  String myString = buffer.toString();

Further to objects comment above:

StringBuilder is faster than StringBuffer.  Use StringBuilder if you can (it is not "thread safe").  If you need it to be thread safe then you'll have to use StringBuffer.  
Mayank SAssociate Director - Product EngineeringCommented:
Keep in mind that StringBuilder is available only in Java 5, so if you have a prior version of Java, you need to stick to StringBuffer.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now