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 */ }
  • 相关阅读:
    C# 桥接模式(Bridge)
    C# 中介者模式(Mediator)
    C# 命令模式(Command)
    C# 模板方法(TempleteMethod)
    C# 装饰模式(Decorate)
    C# 策略模式(Strategy)
    C# 职责链模式(Chain of Responsibility)
    C# 外观模式(Facade)
    C# 单例模式(Single)
    C# 原型模式(Prototype)
  • 原文地址:https://www.cnblogs.com/wangchy0927/p/2755077.html
Copyright © 2011-2022 走看看