fork download
  1. public class Main {
  2.  
  3. public static void main(String[] args) {
  4. int n = 10000;
  5.  
  6. startTimer();
  7. String s1 = repeatString1("hoge", n);
  8. printTime();
  9.  
  10. startTimer();
  11. String s2 = repeatString2("hoge", n);
  12. printTime();
  13.  
  14. System.out.println(s1.equals(s2));
  15. }
  16.  
  17. public static String repeatString1(String s,int n) {
  18. String ret = "";
  19. for(int i=0;i<n;i++) {
  20. ret += s;
  21. }
  22. return ret;
  23. }
  24.  
  25. public static String repeatString2(String s,int n) {
  26. StringBuilder sb = new StringBuilder();
  27. for(int i=0;i<n;i++) {
  28. sb.append(s);
  29. }
  30. return sb.toString();
  31. }
  32.  
  33. private static long stime;
  34. private static void startTimer() {
  35. stime = System.nanoTime();
  36. }
  37. private static void printTime() {
  38. System.out.println((System.nanoTime() - stime) / 1000 + " us");
  39. }
  40. }
  41.  
Success #stdin #stdout 1.09s 320576KB
stdin
Standard input is empty
stdout
969594 us
898 us
true