• 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 */ }
  • 相关阅读:
    linux下安装redis 3.2.1
    redis 登入,检查
    断写了一年的博客~~
    前端面试的感想
    http和web缓存
    http请求报文和响应报文(2)
    http请求报头和响应报头(1)
    网络编程(一)
    防恶意解析,禁止用IP访问网站的Apache设置 修改 httpd.conf 实现
    About English Web Site Font
  • 原文地址:https://www.cnblogs.com/wangchy0927/p/2755077.html
Copyright © 2020-2023  润新知