/**
* 判断字符串为空的三种方法及其效率。
*/
package ch5;
public class StringEmptyCompare {
String s = "";
//循环一亿次,比较效率
long n = 100000000;
//方法1
private void function1() {
//存下起始时间
long startTime = System.currentTimeMillis();
for ( int i = 0; i < n; i ++) {
if (s == null || s.equals("")) ;
}
//存下结束时间
long endTime = System.currentTimeMillis();
System.out.println( "方法1用时:" + (endTime - startTime) + "ms");
}
//方法2
private void function2() {
long startTime = System.currentTimeMillis();
for ( int i = 0; i < n; i ++) {
if (s == null || s.length() < 1) ;
}
long endTime = System.currentTimeMillis();
System.out.println( "方法2用时:" + (endTime - startTime) + "ms");
}
//方法3
private void function3() {
long startTime = System.currentTimeMillis();
for ( int i = 0; i < n; i ++) {
if (s == null || s.isEmpty()) ;
}
long endTime = System.currentTimeMillis();
System.out.println( "方法3用时:" + (endTime - startTime) + "ms");
}
public static void main(String[] args) {
StringEmptyCompare sec = new StringEmptyCompare();
sec.function1();
sec.function2();
sec.function3();
}
}
/**
* Output:
* 方法1用时:1000ms
方法2用时:485ms
方法3用时:609ms
*/
* 判断字符串为空的三种方法及其效率。
*/
package ch5;
public class StringEmptyCompare {
String s = "";
//循环一亿次,比较效率
long n = 100000000;
//方法1
private void function1() {
//存下起始时间
long startTime = System.currentTimeMillis();
for ( int i = 0; i < n; i ++) {
if (s == null || s.equals("")) ;
}
//存下结束时间
long endTime = System.currentTimeMillis();
System.out.println( "方法1用时:" + (endTime - startTime) + "ms");
}
//方法2
private void function2() {
long startTime = System.currentTimeMillis();
for ( int i = 0; i < n; i ++) {
if (s == null || s.length() < 1) ;
}
long endTime = System.currentTimeMillis();
System.out.println( "方法2用时:" + (endTime - startTime) + "ms");
}
//方法3
private void function3() {
long startTime = System.currentTimeMillis();
for ( int i = 0; i < n; i ++) {
if (s == null || s.isEmpty()) ;
}
long endTime = System.currentTimeMillis();
System.out.println( "方法3用时:" + (endTime - startTime) + "ms");
}
public static void main(String[] args) {
StringEmptyCompare sec = new StringEmptyCompare();
sec.function1();
sec.function2();
sec.function3();
}
}
/**
* Output:
* 方法1用时:1000ms
方法2用时:485ms
方法3用时:609ms
*/
转载于:https://blog.51cto.com/violetsky/354958