From cfaed1219f883cc23974342a51444d8fbe84cc45 Mon Sep 17 00:00:00 2001 From: old driver Date: Tue, 25 May 2021 14:19:02 +0800 Subject: [PATCH] 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. --- buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java | 2 +- buffer/src/main/java/io/netty/buffer/ByteBufUtil.java | 6 ++++++ buffer/src/main/java/io/netty/buffer/SwappedByteBuf.java | 3 --- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java b/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java index fb15250271..d16753e257 100644 --- a/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java @@ -1344,7 +1344,7 @@ public abstract class AbstractByteBuf extends ByteBuf { @Override 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 diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java index 675510be51..73d297a815 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java @@ -299,6 +299,9 @@ public final class ByteBufUtil { * This method is useful when implementing a new buffer type. */ public static boolean equals(ByteBuf bufferA, ByteBuf bufferB) { + if (bufferA == bufferB) { + return true; + } final int aLen = bufferA.readableBytes(); if (aLen != bufferB.readableBytes()) { return false; @@ -311,6 +314,9 @@ public final class ByteBufUtil { * This method is useful when implementing a new buffer type. */ public static int compare(ByteBuf bufferA, ByteBuf bufferB) { + if (bufferA == bufferB) { + return 0; + } final int aLen = bufferA.readableBytes(); final int bLen = bufferB.readableBytes(); final int minLength = Math.min(aLen, bLen); diff --git a/buffer/src/main/java/io/netty/buffer/SwappedByteBuf.java b/buffer/src/main/java/io/netty/buffer/SwappedByteBuf.java index 87783c5c95..7e038a6e87 100644 --- a/buffer/src/main/java/io/netty/buffer/SwappedByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/SwappedByteBuf.java @@ -1048,9 +1048,6 @@ public class SwappedByteBuf extends ByteBuf { @Override public boolean equals(Object obj) { - if (this == obj) { - return true; - } if (obj instanceof ByteBuf) { return ByteBufUtil.equals(this, (ByteBuf) obj); }