//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 starttime0 = system.currenttimemillis(); for(int i=0;i<50000;i++){ variables[i] = "hello"; } long endtime0 = system.currenttimemillis(); system.out.println("creation time" + " of string literals : "+ (endtime0 - starttime0) + " ms" ); long starttime1 = system.currenttimemillis(); for(int i=0;i<50000;i++){ variables[i] = new string("hello"); } long endtime1 = 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
以上就是java 实例 - 字符串优化的内容。
