• String判空效率比较


    今天逛社区时忽然看到以下博主时的博文,说字符串判空的效率,觉得口说无凭,于是自己手动测试了一下,以下是我的测试代码,不足之处,还望大神指教

    http://blog.csdn.net/fengxuezhiye/article/details/7763384

    1.下面是测试100万次的代码

     1 package testData;
     2 
     3 public class TestData {
     4     public static void main(String[] args) {
     5         //不需要导入包
     6         //在你的方法第一行加上:
     7         //long a=System.currentTimeMillis();
     8         //在最好的一行加上:
     9         //System.out.println("
    <br>执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");
    10                 String name="";
    11                 String name2="aa";
    12                 String name3=null;
    13         //        测试空
    14         long a=System.currentTimeMillis();
    15         for(int i=0;i<1000000;i++){
    16         if(name == null || name.equals("")){
    17             
    18         }
    19         }
    20         System.out.println("
    <br>执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");    
    21 //        测试长度
    22         long a2=System.currentTimeMillis();
    23         for(int i=0;i<1000000;i++){
    24         if(name == null || name.length() <= 0){
    25         
    26         }
    27         }
    28         System.out.println("
    <br>执行耗时 : "+(System.currentTimeMillis()-a2)/1000f+" 秒 ");    
    29     }
    30 }

    以下是三次运行的效果

    (1)

    (2)

    (3)

    2.下面是1万次的测试结果

      

    3.结果 事实证明  比较长度确实比比较空效率 高

      但是我不甘心如此,又去网上搜了其他资料

    以下是搜集的资料

      1.关于String str =  "abc" 的内部工作。Java内部将此语句转化为以下多个 步骤:      
         
      (1 )先定义一个名为str的对String类的对象引用变量:String str;      
         
      (2 )在栈中查找有没有存放值为 "abc" 的地址,如果没有,则开辟一个存放字面值为 "abc" 的地址,接着建立 一个新的String类的对象o,并将o的字符串值指向这个地址,而且在栈中这个地址旁边记下这个引用的对象o。如果已经有了值为 "abc" 的地址,则查找对象o,并返回o的地址。     
    (3 )将str指向对象o的地址。      
         
      值得留心 的是,一般String类中字符串值都是直接存值的。但像String str = "abc" ;这种场合下,其字符串值却是保存了一个指向存在栈中数据的引用!      
         2.官方的String的equals的重写源码

     1 public boolean equals(Object anObject) {
     2     if (this == anObject) {
     3         return true;
     4     }
     5     if (anObject instanceof String) {
     6         String anotherString = (String)anObject;
     7         int n = count;
     8         if (n == anotherString.count) {
     9         char v1[] = value;
    10         char v2[] = anotherString.value;
    11         int i = offset;
    12         int j = anotherString.offset;
    13         while (n-- != 0) {//看到这忽然就明白了
    14             if (v1[i++] != v2[j++])
    15             return false;
    16         }
    17         return true;
    18         }
    19     }
    20     return false;
    21     }

    瞬间明朗了,吃饭!

  • 相关阅读:
    git 修改文件内容
    centos 7 安装gitlab
    安装Git 创建版本库
    安装 jenkins
    LVS 之搭建
    113. Path Sum II
    112. Path Sum
    111. Minimum Depth of Binary Tree
    110. Balanced Binary Tree
    109.Convert sorted list to BST
  • 原文地址:https://www.cnblogs.com/thehugo/p/5638011.html
Copyright © 2020-2023  润新知