深圳网站建设_,建立网站教程,采集网站会收录吗,如何避免网站被攻击对字符串的性能进行优化#xff0c;找出一种方法能够以最快的时间创建赋值字符串。
我们使用String intern() 的方法来优化字符串。
完整代码
public class Optimization {public static void main(String[] args){String variables[] new String[50000]; for( int i…对字符串的性能进行优化找出一种方法能够以最快的时间创建赋值字符串。
我们使用String intern() 的方法来优化字符串。
完整代码
public class Optimization {public static void main(String[] args){String variables[] new String[50000]; for( int i0;i 50000;i){variables[i] si;}long startTime0 System.currentTimeMillis();for(int i0;i50000;i){variables[i] hello;}long endTime0 System.currentTimeMillis();System.out.println(直接使用字符串 (endTime0 - startTime0) ms );long startTime1 System.currentTimeMillis();for(int i0;i50000;i){variables[i] new String(hello);}long endTime1 System.currentTimeMillis();System.out.println(使用 new 关键字 (endTime1 - startTime1) ms);long startTime2 System.currentTimeMillis();for(int i0;i50000;i){variables[i] new String(hello);variables[i] variables[i].intern(); }long endTime2 System.currentTimeMillis();System.out.println(使用字符串对象的 intern() 方法: (endTime2 - startTime2) ms);}
}结果输出
直接使用字符串 3 ms
使用 new 关键字5 ms
使用字符串对象的 intern() 方法: 10 ms由于初始值的不同所以对比的时间不具有对比性我们应该在同等的条件下计算花费的时间。
完整代码
public class StringOptimization {public static void main(String[] args) {String variables[] new String[50000];long startTime0 System.currentTimeMillis();for (int i 0; i 50000; i) {variables[i] hello;}long endTime0 System.currentTimeMillis();System.out.println(使用字面量直接赋值字符串花费时间 (endTime0 - startTime0) 毫秒);String variables1[] new String[50000];long startTime1 System.currentTimeMillis();for (int i 0; i 50000; i) {variables1[i] new String(hello);}long endTime1 System.currentTimeMillis();System.out.println(使用字符串对象花费时间 (endTime1 - startTime1) 毫秒);String variables2[] new String[50000];long startTime2 System.currentTimeMillis();for (int i 0; i 50000; i) {variables2[i] new String(hello);variables2[i] variables2[i].intern();}long endTime2 System.currentTimeMillis();System.out.println(使用字符串对象intern()方法花费时间 (endTime2 - startTime2) 毫秒);}
}结果输出
使用字面量直接赋值字符串花费时间1毫秒
使用字符串对象花费时间3毫秒
使用字符串对象intern()方法花费时间8毫秒