String判空效率比较

(导入自己博客园的文章)

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("\r<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("\r<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("\r<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     }
复制代码

瞬间明朗了,吃饭!

标签: 性能
0
0

« 上一篇: myeclipse数据库逆向hibernate教程
» 下一篇: 干货分享,排序自己收集的单词,并且计算是否重复
    </div>
    <div class="postDesc">posted @ <span id="post-date">2016-07-03 14:59</span> <a href="http://www.cnblogs.com/thehugo/">果果爱吃苹果</a> 阅读(<span id="post_view_count">75</span>) 评论(<span id="post_comment_count">0</span>)  <a href="https://i.cnblogs.com/EditPosts.aspx?postid=5638011" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(5638011);return false;">收藏</a></div>
</div>

猜你喜欢

转载自blog.csdn.net/mengxiangxingdong/article/details/78867212