Skip to content

Instantly share code, notes, and snippets.

@soheil-ghahremani
Created August 23, 2019 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soheil-ghahremani/ba4c63a5b676137cf6e96fedc380a55c to your computer and use it in GitHub Desktop.
Save soheil-ghahremani/ba4c63a5b676137cf6e96fedc380a55c to your computer and use it in GitHub Desktop.
difference between String and StringBuilder and StringBuffer
package ir.soheil_gh;
public class StringTest {
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
String initialString = "";
for(int i=0; i<50000; i++ ){
initialString += i;
}
long t2 = System.currentTimeMillis();
System.out.println(t2 - t1 + " milliseconds");
StringBuilder initialStringBuilder = new StringBuilder();
long t3 = System.currentTimeMillis();
for(int i=0; i<50000; i++ ){
initialStringBuilder.append(i);
}
long t4 = System.currentTimeMillis();
System.out.println(t4 - t3 + " milliseconds");
StringBuffer initialStringBuffer = new StringBuffer();
long t5 = System.currentTimeMillis();
for(int i=0; i<50000; i++ ){
initialStringBuffer.append(i);
}
long t6 = System.currentTimeMillis();
System.out.println(t6 - t5 + " milliseconds");
}
}
@soheil-ghahremani
Copy link
Author

soheil-ghahremani commented Aug 23, 2019

output :
7079 milliseconds
2 milliseconds
3 milliseconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment