67,513
社区成员
发帖
与我相关
我的任务
分享
StringBuffer upp = new StringBuffer(),
low = new StringBuffer();
for(int i = 0; i<=9000000; i++){
upp.append("AA");
low.append("aa");
}
long Tupp = System.currentTimeMillis();
upp.toString().toUpperCase();
System.out.println("UPP:"+(System.currentTimeMillis()-Tupp));
long Tlow = System.currentTimeMillis();
low.toString().toUpperCase();
System.out.println("LOW:"+(System.currentTimeMillis()-Tlow));
public String toUpperCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstLower;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstLower = 0 ; firstLower < count; ) {
int c = (int)value[offset+firstLower];
int srcCount;
if ((c >= Character.MIN_HIGH_SURROGATE) &&
(c <= Character.MAX_HIGH_SURROGATE)) {
c = codePointAt(firstLower);
srcCount = Character.charCount(c);
} else {
srcCount = 1;
}
int upperCaseChar = Character.toUpperCaseEx(c);
if ((upperCaseChar == Character.ERROR) ||
(c != upperCaseChar)) {
break scan;
}
firstLower += srcCount;
}
return this;
}
好好看下这段代码StringBuffer upp = new StringBuffer(), low = new StringBuffer();
for (int i = 0; i <= 9000000; i++) {
upp.append("Aa");
low.append("aa");
}
long Tupp = System.currentTimeMillis();
upp.toString().toUpperCase();
System.out.println("UPP:" + (System.currentTimeMillis() - Tupp));
long Tlow = System.currentTimeMillis();
low.toString().toUpperCase();
System.out.println("LOW:" + (System.currentTimeMillis() - Tlow));
long Tupp2 = System.currentTimeMillis();
upp.toString().toUpperCase();
System.out.println("UPP:" + (System.currentTimeMillis() - Tupp2));
for(int i = 0; i<=9000000; i++){
upp.append("Aa");
low.append("Aa");
}
//代码块1
long Tupp = System.currentTimeMillis();
upp.toString().toUpperCase();
System.out.println("UPP:"+(System.currentTimeMillis()-Tupp));
//代码块1
//代码块2
long Tlow = System.currentTimeMillis();
low.toString().toLowerCase();
System.out.println("LOW:" + (System.currentTimeMillis() - Tlow));
//代码块2
//代码块3
long Tupp2 = System.currentTimeMillis();
upp.toString().toUpperCase();
System.out.println("UPP:" + (System.currentTimeMillis() - Tupp2));
//代码块3
这个代码你去执行下。
代码块3和1都是一样的。我执行的结果是 1的时间永远比2多。但是2和3的大小是不一定的。
我觉得原因在于1执行的时候要加载一些toUpperCase方法涉及到得类和方法。
所以1慢,但是2和3的时候加载过了。自然就快了。转换过程中涉及CPU占用,有时候执行toUpperCase时分配到得时间片足够执行,耗时少。有时候反而是转小写能够执行的更多(操作系统对线程调度,你没法控制,jvm也没办法。)
所以大小写转换方法效率几乎是一样的。
ps,C#中微软有针对转大写方法的特别优化,所以一般选择转大写后比较字符串。