在Android 的開發中經常會使用判斷字符串是否為空,雖然現在智能手機的運行速度越來越高,但為了使應用更加的流暢,我們應該保證
在編寫程序時使用較好的方法來提高效率。一下為四種方法的運行時間的比較:
public class TestEmptyString {
String s = "";
long n = 10000000;
private void function1() {
long startTime = System.currentTimeMillis();
for (long i = 0; i < n; i++) {
if (s == null || s.equals(""))
;
}
long endTime = System.currentTimeMillis();
System.out.println("function 1 use time: " + (endTime - startTime)
+ "ms");
}
private void function2() {
long startTime = System.currentTimeMillis();
for (long i = 0; i < n; i++) {
if (s == null || s.length() <= 0)
;
}
long endTime = System.currentTimeMillis();
System.out.println("function 2 use time: " + (endTime - startTime)
+ "ms");
}
private void function3() {
long startTime = System.currentTimeMillis();
for (long i = 0; i < n; i++) {
if (s == null || s.isEmpty())
;
}
long endTime = System.currentTimeMillis();
System.out.println("function 3 use time: " + (endTime - startTime)
+ "ms");
}
private void function4() {
long startTime = System.currentTimeMillis();
for (long i = 0; i < n; i++) {
if (s == null || s == "")
;
}
long endTime = System.currentTimeMillis();
System.out.println("function 4 use time: " + (endTime - startTime)
+ "ms");
}
public static void main(String[] args) {
TestEmptyString test = new TestEmptyString();
test.function1();
test.function2();
test.function3();
test.function4();
}