fork(2) download
  1.  
  2. import java.util.*;
  3. import java.lang.*;
  4. import java.io.*;
  5.  
  6. public class Main {
  7.  
  8. private static int loop1(List<String> list) {
  9. int charCount = 0;
  10. for (int i = 0; i < list.size(); i++) {
  11. charCount += list.get(i).length();
  12. }
  13. return charCount;
  14. }
  15.  
  16. private static int loop2(List<String> list) {
  17. int charCount = 0;
  18. int listCount = list.size();
  19. for (int i = 0; i < listCount; i++) {
  20. charCount += list.get(i).length();
  21. }
  22. return charCount;
  23. }
  24.  
  25. private static int loop3(List<String> list) {
  26. int charCount = 0;
  27. for (String s : list) {
  28. charCount += s.length();
  29. }
  30. return charCount;
  31. }
  32.  
  33. public static void main(String[] args) {
  34. ArrayList<String> ls = new ArrayList<String>();
  35.  
  36. for (int j = 0; j < 1000000; j++) {
  37. ls.add("one");
  38. ls.add("two");
  39. ls.add("three");
  40. ls.add("four");
  41. ls.add("five");
  42. }
  43.  
  44. long startTime1 = System.nanoTime();
  45. int count1 = loop1(ls);
  46. long elapsed1 = System.nanoTime() - startTime1;
  47.  
  48. long startTime2 = System.nanoTime();
  49. int count2 = loop2(ls);
  50. long elapsed2 = System.nanoTime() - startTime2;
  51.  
  52. long startTime3 = System.nanoTime();
  53. int count3 = loop3(ls);
  54. long elapsed3 = System.nanoTime() - startTime3;
  55.  
  56. System.out.println("Elapsed1: " + elapsed1 + " ns");
  57. System.out.println("Elapsed2: " + elapsed2 + " ns");
  58. System.out.println("Elapsed3: " + elapsed3 + " ns");
  59. }
  60.  
  61. }
Success #stdin #stdout 0.63s 320576KB
stdin
Standard input is empty
stdout
Elapsed1: 99760529 ns
Elapsed2: 59375177 ns
Elapsed3: 90220306 ns