String,StringBuilder,StringBuffer时间比较

 String,StringBuilder,StringBuffer时间比较

 

 

 结论:

对象类型:常量,变量,变量 ——》联想记忆方式:一常 两变

线程安全:不安全,不安全,安全   ——》联想记忆方式:两 不 一 安

String执行效率 < StringBuffer的执行效率 < StringBuilder的执行效率   ——》联想记忆方式:在26个英文字母中 f 在 i 前面 所以StringBuffer的执行效率 < StringBuilder的执行效率

 

 1 package com.cst.iprocess.controller;
 2 import java.util.Date;
 3 
 4 public class test {
 5 
 6     public static void main(String[] args) {
 7         //String,StringBuilder,StringBuffer时间比较
 8         //String
 9         String str = "";//创建新字符串
10         long starTime = System.currentTimeMillis();//定义字符串执行操作的开始时间
11         for(int i = 0;i<10000;i++) {//for循环
12             str=str+i;//循环追加字符串
13         }
14         long endTime = System.currentTimeMillis();//定义字符串执行操作的结束时间
15         long time = endTime - starTime;//计算对字符串操作前后的时间
16         System.out.println("String的执行时间为:"+time);//打印出结果
17         
18         //StringBuilder
19         StringBuilder std = new StringBuilder();//创建字符串生成器
20          starTime = System.currentTimeMillis();//定义字符串执行操作的开始时间
21         for(int i = 0;i<10000;i++) {//for循环
22             std.append(i);//循环追加字符串
23         }
24          endTime = System.currentTimeMillis();//定义字符串执行操作的结束时间
25          time = endTime - starTime;//计算对字符串操作前后的时间
26          System.out.println("StringBuilder的执行时间为:"+time);//打印出结果
27          
28         //StringBuffer
29         StringBuffer stb = new StringBuffer();//创建字符串生成器
30          starTime = System.currentTimeMillis();//定义字符串执行操作的开始时间
31         for(int i = 0;i<10000;i++) {//for循环
32             stb.append(i);//循环追加字符串
33         }
34          endTime = System.currentTimeMillis();//定义字符串执行操作的结束时间
35          time = endTime - starTime;//计算对字符串操作前后的时间
36          System.out.println("StringBuffer的执行时间为:"+time);//打印出结果
37     }
38 }
 

 

执行时间

1 String的执行时间为:145 
2
StringBuilder的执行时间为:1
3
StringBuffer的执行时间为:0

 

posted @ 2019-05-08 15:06  贩卖长江水  阅读(422)  评论(0编辑  收藏  举报