oDiBo “开封菜”WWW.KFC.IM

KFC.im记录学习、工作、生活中的点点滴滴…
posts - 51, comments - 0, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Java判断字符串是否为空的三种方法

Posted on 2009-06-15 13:46 London2012 阅读(105) 评论(0)  编辑  收藏 所属分类: CODE

方法一: 最多人使用的一个方法, 直观, 方便, 但效率很低。

    方法二: 比较字符串长度, 效率高, 是我知道的最好一个方法。

    方法三: Java SE 6.0 才开始提供的方法, 效率和方法二几乎相等, 但出于兼容性考虑, 推荐使用方法二。

    以下代码在我机器上的运行结果: (机器性能不一, 仅供参考)

 function 1 use time: 141ms
 function 
2 use time: 46ms
 function 
3 use time: 47ms
 
*/
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();
 }

}


本文来自CSDN博客,转载请标明出处:http:
//blog.csdn.net/huzhen919/archive/2009/06/14/4268323.aspx

只有注册用户登录后才能发表评论。


网站导航: