zoukankan      html  css  js  c++  java
  • 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. }  
  • 相关阅读:
    盘点黑客攻击途径:最常用的7个策略及简单的防护方法
    python 小技巧
    vi 使用方法
    Mac下添加环境变量(一劳永逸)
    增强for循环
    十大排序算法
    java中break、continue、return作用
    Mac zsh中所有命令失效
    Mac 每次都要执行source ~/.bash_profile 后,配置的环境变量才生效
    Mac下添加环境变量
  • 原文地址:https://www.cnblogs.com/interdrp/p/5062442.html
Copyright © 2011-2022 走看看