zoukankan      html  css  js  c++  java
  • 20180914-Java实例03


    Java 实例 – 字符串性能比较测试


    以下实例演示了通过两种方式创建字符串,并测试其性能:


    // StringComparePerformance.java 文件

    public class StringComparePerformance{
    public static void main(String[] args){
    long startTime = System.currentTimeMillis();
    for(int i=0;i<50000;i++){
    String s1 = "hello";
    String s2 = "hello";
    }

    long endTime = System.currentTimeMillis();

    System.out.prinln("通过String 关键字创建字符串"
    +":" +(endTime - startTime) + "毫秒");

    long startTime1 = System.currentTimeMillis();
    for(int i=0;i<50000;i++){
    String s3 = new String("hello");
    String s4 = new String("hello");
    }

    long endTimel = System.currentTimeMillis();
    System.out.println("通过 String 对象创建字符串"
    +":" +(endTimel - startTimel) + "毫秒"
    );

    }

    }

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

    通过 String 关键词创建字符串 : 6 毫秒
    通过 String 对象创建字符串 : 14 毫秒


    Java 实例 – 字符串优化

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


    // StringOptimization.java 文件


    public class StringOptimization{
    public static void main(String[] args){
    String variables[] = new String[50000];
    for(int i=0;i<50000;i++){
    variables[i] = "s" + i;
    }
    long startTime() = System.currentTimeMillis();

    for(int i=0;i<50000;i++){
    variables[i] = "hello";
    }

    long endTime() = System.currentTimeMillis();
    System.out.println("Creation time"
    + " of String literals : "+ (endTime0 - startTime0)
    + " ms")

    long startTimel = System.crrentTimeMillis();
    for(int i=0;i<50000;i++){
    variables[i] = new String("hello");
    }

    long endTimel = System.currentTimeMillis();
    System.out.println("Creation time of"
    + " String objects with 'new' key word : "
    + (endTime1 - startTime1)
    + " ms");

    long startTime2 = System.currentTimeMillis();
    for(int i=0;i<50000;i++){
    variables[i] = new String("hello");
    variables[i] = variables[i].intern();
    }

    long endTime2 = System.currentTimeMillis();
    System.out.println("Creation time of"
    + " String objects with intern(): "
    + (endTime2 - startTime2)
    + " ms");
    }
    }

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


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

  • 相关阅读:
    bzoj1662: [Usaco2006 Nov]Round Numbers 圆环数
    畅通工程——D
    Constructing Roads——F
    FatMouse's Speed——J
    Tickets——H
    免费馅饼——G
    Max Sum Plus Plus——A
    Super Jumping! Jumping! Jumping!——E
    Fling——K
    #define is unsafe——I
  • 原文地址:https://www.cnblogs.com/Alanf/p/9648466.html
Copyright © 2011-2022 走看看