• String,StringBuilder性能对照


    import java.util.Date;
    import java.util.UUID;


    /**
     * 測试String,StringBuilder性能,推断什么时候改用String,什么时候该用StringBuilder
     * 測试结果

     * String              拼接測试,測试长度10000,測试字符串数组长度30,完毕时间721

       StringBuilder 拼接測试,測试长度10000,測试字符串数组长度30,完毕时间315

       String              拼接測试,測试长度10000,測试字符串数组长度10,完毕时间301

       StringBuilder 拼接測试,測试长度10000,測试字符串数组长度10,完毕时间124

       String              拼接測试,測试长度10000,測试字符串数组长度5,完毕时间237

       StringBuilder 拼接測试,測试长度10000,測试字符串数组长度5,完毕时间68

       String              拼接測试,測试长度10000,測试字符串数组长度50,完毕时间1169

       StringBuilder 拼接測试,測试长度10000,測试字符串数组长度50,完毕时间504

       String     拼接測试,測试长度10000,測试字符串数组长度2,完毕时间188

       StringBuilder 拼接測试,測试长度10000,測试字符串数组长度2,完毕时间31

       String              拼接測试,測试长度20000,測试字符串数组长度2,完毕时间253
       StringBuilder 拼接測试,測试长度20000,測试字符串数组长度2,完毕时间59

     * 
     * 这几组至少是2倍以上的时间差距,
     * 当然小范围的拼接差点儿时间都是能够忽略不计的,可是你假设作为工具类或者大范围的拼接不妨用StringBuilder,哪怕仅仅是拼接两个字符串
     * @author JueYue
     * 
     */
    public class StringTest {


    public static void main(String[] args) {
    int testLength = 10000;
    String[] arr = new String[2];
    Date start = new Date();
    String str = "";
    for (int i = 0; i < testLength; i++) {
    str = "";
    for (int j = 0; j < arr.length; j++) {
    str += UUID.randomUUID().toString();
    }
    }
    System.out.println("String 拼接測试,測试长度" + testLength + ",測试字符串数组长度"
    + arr.length + ",完毕时间"
    + (new Date().getTime() - start.getTime()));
    start = new Date();
    StringBuilder sb;
    for (int i = 0; i < testLength; i++) {
    sb = new StringBuilder();
    for (int j = 0; j < arr.length; j++) {
    sb.append(UUID.randomUUID().toString());
    }
    }
    System.out.println("StringBuilder 拼接測试,測试长度" + testLength + ",測试字符串数组长度"
    + arr.length + ",完毕时间"
    + (new Date().getTime() - start.getTime()));
    }


    }
  • 相关阅读:
    Trapping Rain Water
    Construct Binary Tree from Preorder and Inorder Traversal
    Flatten Binary Tree to Linked List
    Permutations II
    Unique Paths II
    Path Sum II
    Unique Binary Search Trees II
    evdev module-----uinput.py
    evdev module-----events.py
    evdev module-----device.py
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7235792.html
Copyright © 2020-2023  润新知