Java中判断String不为空的问题性能比较

 function 1: 最多人使用的一个方法, 直观, 方便, 但效率很低.
 function 2: 比较字符串长度, 效率高, 是我知道的最好一个方法.
 function 3: Java SE 6.0 才开始提供的方法, 效率和方法二几乎相等, 但出于兼容性考虑, 不推荐使用

   以下是三种方法在机器上的运行结果: (机器性能不一, 仅供参考)
 function 1 use time: 141ms
 function 2 use time: 46ms
 function 3 use time: 47ms

三种方法的代码如下:

  方法一:

  

Java代码  收藏代码
  1. public void function1(String s,int n) {  
  2.   long startTime = System.currentTimeMillis();  
  3.    
  4.   for(long i = 0; i<n; i++) {  
  5.    if(s == null || s.equals(""));  
  6.   }  
  7.   long endTime = System.currentTimeMillis();  
  8.    
  9.   System.out.println("function 1 use time: "+ (endTime - startTime) +"ms");  
  10.  }  

 方法二:

  

Java代码  收藏代码
  1. public void function2(String str,int n) {  
  2.   long startTime = System.currentTimeMillis();  
  3.    
  4.   for(long i = 0; i< n; i++) {  
  5.    if(s == null || s.length() <= 0);  
  6.   }  
  7.   long endTime = System.currentTimeMillis();  
  8.    
  9.   System.out.println("function 2 use time: "+ (endTime - startTime) +"ms");  
  10.  }  

方法三:

  

Java代码  收藏代码
  1. public void function3(String str , int n) {  
  2.   long startTime = System.currentTimeMillis();  
  3.    
  4.   for(long i = 0; i <n; i++) {  
  5.       if(s == null || s.isEmpty());  
  6.   }  
  7.   long endTime = System.currentTimeMillis();  
  8.    
  9.   System.out.println("function 3 use time: "+ (endTime - startTime) +"ms");  
  10.    
  11. }  
原文地址:https://www.cnblogs.com/interdrp/p/5062442.html