判断 Java 中的空字符串
生活随笔
收集整理的這篇文章主要介紹了
判断 Java 中的空字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文地址:http://www.neoease.com/string-is-empty/
以下是 Java 判斷字符串是否為空的三種方法.
方法一: 最多人使用的一個方法, 直觀, 方便, 但效率很低.
方法二: 比較字符串長度, 效率高, 是我知道的最好一個方法.
方法三: Java SE 6.0 才開始提供的方法, 效率和方法二幾乎相等, 但出于兼容性考慮, 推薦使用方法二.
以下代碼在我機器上的運行結果: (機器性能不一, 僅供參考)
function 1 use time: 172ms
function 2 use time: 78ms
function 3 use time: 79ms
?
public class CompareStringNothing {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");}public static void main(String[] args) {CompareStringNothing com = new CompareStringNothing();com.function1();com.function2();com.function3();} }轉載于:https://www.cnblogs.com/suman/archive/2010/10/26/1861521.html
總結
以上是生活随笔為你收集整理的判断 Java 中的空字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 移动wabAPP 开发 viewport
- 下一篇: Java Date Time 教程-时间