• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 154
  • 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.

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

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