学习mybatis源码疑惑一

一、背景

在学习mybatis源码时,在类org.apache.ibatis.datasource.pooled.PooledConnection 中发现一些程序片段


其中:变量CLOSE定义为 private static final String CLOSE = "close"

变量methodName也为String类型

二、疑惑描述

mybatis的作者在比较字符串时,为什么要先调用hashCode()进行比较,再调用equals方法?

三、猜测

因为jdk规范要求如果两个对象的equals()为true,那么它们的hashcode()的值必相等。mybatis的作者先用字符串的hashcode()进行比较,可以提高字符串的比较效率。

但是,如果先比较hashcode值可以提高字符串比较效率,为什么String.equals()方法中,没有先比较hashcode值呢?

四、验证

用junit写了个单元测试用例进行验证,代码如下:

package com.apex.mq.rabbitmq.interotc.client;

import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class StringTest {
	private static final String CLOSE = "close";

	private String name;
	private boolean expected;

	@Parameters(name = "test compare consume time: {index}: when ({0})={1}")
	public static Iterable<Object[]> data1() {
		return Arrays.asList(new Object[][] { { "close", true },
				{ "equals", true }, { "toString", true }, { "hashcode", true },
				{ "getClass", true }, { "clone", true }, { "notify", true },
				{ "notifyAll", true }, { "wait", true } });
	}

	public StringTest(String name, boolean expected) {
		this.name = name;
		this.expected = expected;
	}

	@Test
	public void testConsumeTime() {
		assertEquals(expected, testHashCode() < testEquals());
	}

	private long testHashCode() {
		long beforeTimeMillis = System.currentTimeMillis();
		for (int i = 0; i < 1000000; i++) {
			boolean result = CLOSE.hashCode() == name.hashCode();
			result = false;
		}
		long endTimeMillis = System.currentTimeMillis();
		long consumeTime = endTimeMillis - beforeTimeMillis;
		System.out.println("Method: hashCode() consume time: " + consumeTime
				+ " when the string is " + name);
		return consumeTime;
	}

	private long testEquals() {
		long beforeTimeMillis = System.currentTimeMillis();
		for (int i = 0; i < 1000000; i++) {
			boolean result = CLOSE.equals(name);
			result = false;
		}
		long endTimeMillis = System.currentTimeMillis();
		long consumeTime = endTimeMillis - beforeTimeMillis;
		System.out.println("Method: equals() consume time: " + consumeTime
				+ " when the string is " + name);
		System.out.println();
		return endTimeMillis - beforeTimeMillis;
	}

}
执行结果出乎意料, hashcode()并没有equals()效率高,如下图:





五、结论(欢迎拍砖)

1、通过单元测试发现,hashcode()并没有equals()效率高,所以mybatis作者的这种写法,可能只是下意识认为这样效率高。


六、后续疑问

这种写法,会不会在大量、相似、很长的字符串比较中效率高?


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值