字符串优化

字符串优化

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("直接使用字符串:"+(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("使用 new 关键字:" + (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("使用字符串对象的 intern() 方法:" + (endTime2 - startTime2) + "ms");

}

}

 

字符串搜索

public class SearchStringEmp {//字符串搜索

public static void main(String[] args) {

String strOrig = "Google Runoob Taobao";

int intIndex = strOrig.indexOf("Runoob");

if(intIndex == -1) {

System.out.println("没有找到字符串 Runoob");

}else {

System.out.println("Runoob 字符串位置 "+ intIndex);

}

}

}

 

posted @ 2022-05-04 21:33  慢漫曼蔓  阅读(50)  评论(0)    收藏  举报