java - 与 equals 相比,== 运算符的使用如何带来性能改进?

标签 java performance equals referenceequals

在Joshua Bloch的Effective JAVA中,当我在阅读静态工厂方法时,有如下声明

The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton (Item 3) or noninstantiable (Item 4). Also, it allows an immutable class (Item 15) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its cli- ents can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types (Item 30) provide this guarantee.

为了研究 == 运算符如何带来性能改进, 我得看看String.java

我看到了这个片段

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

性能提升是什么意思?它如何带来性能提升。

他是不是想说下面的话

如果每个类都可以确保 a.equals(b) 当且仅当 a==b 时,这意味着它带来了一个间接要求,即不能有对象引用 2 个不同的内存空间并且仍然持有同样的数据,这是内存浪费。如果它们保存相同的数据,那么它们就是同一个对象。也就是说,它们指向相同的内存位置。

我的推论对吗?

如果我错了,你能指导我理解吗?

最佳答案

If every class can assure that a.equals(b) if and only if a==b , it means it brings in an indirect requirement that there cannot be objects referring to 2 different memory spaces and still hold the same data , which is memory wastage . If they hold same data they are one and the same object .That is they point to same memory location.

是的,这就是作者的目的。

如果你可以(对于给定的类,这对所有类都是不可能的,特别是它不能用于可变类)调用 == (这是单个 JVM 操作码)而不是 equals(这是一个动态调度的方法调用),它节省了(一些)开销。

例如,它以这种方式用于 enum

即使有人调用了 equals 方法(这将是很好的防御性编程实践,您也不想养成对对象使用 == 的习惯恕我直言),该方法可以作为简单的 == 实现(而不必查看潜在的复杂对象状态)。

顺便说一句,即使对于“普通”equals 方法(例如 String 的),在它们的实现中首先检查对象标识然后查看对象状态的捷径(这就是 String#equals 所做的)可能是一个好主意,正如您所发现的那样)。

关于java - 与 equals 相比,== 运算符的使用如何带来性能改进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20027495/

相关文章:

java - Spring Bean Overriding 在 JpaAuditingRegistrar 中抛出错误

java - 平面组织结构到 Java 中的 TreeView

performance - JPA单向@OneToMany性能

java - 编译器或 JVM 是否强制执行 hashCode/equals 约定?

java - MongoJack 和 updateById 的使用

Java无线模块开发

java - HashTable 类的包含问题

Java equals() 和 hashCode() 变化

android - 缓慢的音乐加载算法

java - 即使没有为它们指定代码,Android Activity 生命周期方法是否有用?