zoukankan      html  css  js  c++  java
  • java的Equal

    JDK中Equal的源码如下所示: 

     public boolean equals(Object anObject) {
    	if (this == anObject) {
    	    return true;
    	}
    	if (anObject instanceof String) {
    	    String anotherString = (String)anObject;
    	    int n = count;
    	    if (n == anotherString.count) {
    		char v1[] = value;
    		char v2[] = anotherString.value;
    		int i = offset;
    		int j = anotherString.offset;
    		while (n-- != 0) {
    		    if (v1[i++] != v2[j++])
    			return false;
    		}
    		return true;
    	    }
    	}
    	return false;
        }
    

    通过如下的例子验证:

      第一次走到this == anObject返回ture,第二次走完全部,第三次走到if (n == anotherString.count)返回false,所以时间为time1 = 63 time2 = 391 time3 = 78


    public void StringEqual() {
    		String a = "HelloWorld";
    		String b = "HelloWorld";
    		long start1 = System.currentTimeMillis(); // <+++ Start timing
    		for (int i = 0; i < 10000000; i++)
    			a.equals(b);
    		long stop1 = System.currentTimeMillis(); // <+++ Stop timing
    		System.out.println(" time1 = " + (stop1 - start1));//走到this == anObject返回ture
    String c = "HelloWorld"; String d = "HelloWorlD"; long start2 = System.currentTimeMillis(); // <+++ Start timing for (int i = 0; i < 10000000; i++) c.equals(d); long stop2 = System.currentTimeMillis(); // <+++ Stop timing System.out.println(" time2 = " + (stop2 - start2));//走完全部 String e = "HelloWorld"; String f = "HelloWorld1"; long start3 = System.currentTimeMillis(); // <+++ Start timing for (int i = 0; i < 10000000; i++) e.equals(f); long stop3 = System.currentTimeMillis(); // <+++ Stop timing System.out.println(" time3 = " + (stop3 - start3));//走到if (n == anotherString.count)返回false
    /* * System.out.println(); time1 = 63 time2 = 391 time3 = 78 */ }
  • 相关阅读:
    mysql中GROUP_CONCAT的使用
    sublime text3 配置
    dede自定义标签
    mysql索引
    mysql5.5以上开启慢查询
    mysql定位慢查询
    mysql5.5以上my.ini中设置字符集
    mysql数据库的优化
    win下Apache2.4的下载与安装
    PHP Warning: PHP Startup: in Unknown on line 0
  • 原文地址:https://www.cnblogs.com/wangchy0927/p/2755077.html
Copyright © 2011-2022 走看看