Java 实例 - 字符串优化


以下实例演示了通过 String.intern() 方法来优化字符串:

  1. //StringOptimization.java 文件
  2.  
  3. public class StringOptimization{
  4. public static void main(String[] args){
  5. String variables[] = new String[50000];
  6. for( int i=0;i <50000;i++){
  7. variables[i] = "s"+i;
  8. }
  9. long startTime0 = System.currentTimeMillis();
  10. for(int i=0;i<50000;i++){
  11. variables[i] = "hello";
  12. }
  13. long endTime0 = System.currentTimeMillis();
  14. System.out.println("Creation time"
  15. + " of String literals : "+ (endTime0 - startTime0)
  16. + " ms" );
  17. long startTime1 = System.currentTimeMillis();
  18. for(int i=0;i<50000;i++){
  19. variables[i] = new String("hello");
  20. }
  21. long endTime1 = System.currentTimeMillis();
  22. System.out.println("Creation time of"
  23. + " String objects with 'new' key word : "
  24. + (endTime1 - startTime1)
  25. + " ms");
  26. long startTime2 = System.currentTimeMillis();
  27. for(int i=0;i<50000;i++){
  28. variables[i] = new String("hello");
  29. variables[i] = variables[i].intern();
  30. }
  31. long endTime2 = System.currentTimeMillis();
  32. System.out.println("Creation time of"
  33. + " String objects with intern(): "
  34. + (endTime2 - startTime2)
  35. + " ms");
  36. }
  37. }

以上代码实例输出结果为:

  1. Creation time of String literals : 0 ms
  2. Creation time of String objects with 'new' key word : 31 ms
  3. Creation time of String objects with intern(): 16 ms