Add fast path in ByteBufUtil.compare and ByteBufUtil.equals methods (#11296)

Motivation:

When object-references are both same, the method should return 0 directly with no necessary go loop&compare the content of the ByteBuf.

Modification:

Added short circuit when both object-references are the same for equals and compare methods.

Result:

Added short circuit code.
This commit is contained in:
old driver 2021-05-25 14:19:02 +08:00 committed by GitHub
parent 7b064700a0
commit cfaed1219f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 7 additions and 4 deletions

View File

@ -1344,7 +1344,7 @@ public abstract class AbstractByteBuf extends ByteBuf {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
return this == o || (o instanceof ByteBuf && ByteBufUtil.equals(this, (ByteBuf) o)); return o instanceof ByteBuf && ByteBufUtil.equals(this, (ByteBuf) o);
} }
@Override @Override

View File

@ -299,6 +299,9 @@ public final class ByteBufUtil {
* This method is useful when implementing a new buffer type. * This method is useful when implementing a new buffer type.
*/ */
public static boolean equals(ByteBuf bufferA, ByteBuf bufferB) { public static boolean equals(ByteBuf bufferA, ByteBuf bufferB) {
if (bufferA == bufferB) {
return true;
}
final int aLen = bufferA.readableBytes(); final int aLen = bufferA.readableBytes();
if (aLen != bufferB.readableBytes()) { if (aLen != bufferB.readableBytes()) {
return false; return false;
@ -311,6 +314,9 @@ public final class ByteBufUtil {
* This method is useful when implementing a new buffer type. * This method is useful when implementing a new buffer type.
*/ */
public static int compare(ByteBuf bufferA, ByteBuf bufferB) { public static int compare(ByteBuf bufferA, ByteBuf bufferB) {
if (bufferA == bufferB) {
return 0;
}
final int aLen = bufferA.readableBytes(); final int aLen = bufferA.readableBytes();
final int bLen = bufferB.readableBytes(); final int bLen = bufferB.readableBytes();
final int minLength = Math.min(aLen, bLen); final int minLength = Math.min(aLen, bLen);

View File

@ -1048,9 +1048,6 @@ public class SwappedByteBuf extends ByteBuf {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof ByteBuf) { if (obj instanceof ByteBuf) {
return ByteBufUtil.equals(this, (ByteBuf) obj); return ByteBufUtil.equals(this, (ByteBuf) obj);
} }