62,614
社区成员
发帖
与我相关
我的任务
分享
String str = "";
for(int i=0;i < 5;i++){
str = i+"";
//下面处理str其他操作
}
for(int i=0;i < 5;i++){
String str = i+"";
//下面处理str其他操作
}
//看看吧
String str = null ;
for(int i=0;i < 5;i++){
str = String.valueOf( i ) ;
//下面处理str其他操作 操作完之后 将 str清空
//这样可以提前销毁该对象,不需要系统一直保留该对象。
str = null ;
}
package card;
public class Test {
public static void main(String[] args) {
System.out.println(timeCost(1));
System.out.println(timeCost(2));
}
public static long timeCost(int i) {
long startTime = System.currentTimeMillis();
if (i == 1) {
test1();
}else {
test2();
}
long endTime = System.currentTimeMillis();
return endTime - startTime;
}
public static void test1() {
String str = null;
for (int i = 0; i < 20000000; i+=2){
str = i + "";
}
}
public static void test2() {
for (int i = 1; i < 20000000; i+=2) {
String str = i + "";
}
}
}
long startTime=System.currentTimeMillis();//开始
long endTime=System.currentTimeMillis();//结束
long t1 = System.nanoTime();
for(int i=0;i < 50000;i++){
String str01 = i+"";
//下面处理str其他操作
}
long t2 = System.nanoTime();
System.out.println(t2 - t1);
long t3 = System.nanoTime();
String str = "";
for(int i=0;i < 50000;i++){
str = i+"";
//下面处理str其他操作
}
long t4 = System.nanoTime();
System.out.println(t4 - t3);