Skip to content

chore: Make use of eq and nq #466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft

Conversation

He-Pin
Copy link
Contributor

@He-Pin He-Pin commented Aug 2, 2025

Motivation:
eq and ne should be faster.

Copy link
Contributor

@JoshRosen JoshRosen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Motivation:
eq and ne should be faster.

I don't think that this is the case when comparing AnyRef to a literal null, at least not in any in modern Scala versions.

Consider:

class C {
  def f(x: AnyRef): Boolean = (x == null)
  def g(x: AnyRef): Boolean = (x eq null)
}

In Scala 2.13.2, via javap -c -v target/scala-2.13/classes/C.class, these compile to identical bytecode where both use the ifnonnull instruction:

public boolean f(java.lang.Object);
    descriptor: (Ljava/lang/Object;)Z
    flags: (0x0001) ACC_PUBLIC
    Code:
      stack=1, locals=2, args_size=2
         0: aload_1
         1: ifnonnull     8
         4: iconst_1
         5: goto          9
         8: iconst_0
         9: ireturn
[...]

public boolean g(java.lang.Object);
    descriptor: (Ljava/lang/Object;)Z
    flags: (0x0001) ACC_PUBLIC
    Code:
      stack=1, locals=2, args_size=2
         0: aload_1
         1: ifnonnull     8
         4: iconst_1
         5: goto          9
         8: iconst_0
         9: ireturn
[...]

Similarly, I also don't see a difference in bytecode for the ne case. I also don't see any bytecode differences in Scala 2.12, Scala 3, etc.

Edit: to be clear, eq and ne could potentially make a performance difference in cases where you're doing more than a null check and only need reference equality, but I don't think it makes a difference for null checks.

@He-Pin
Copy link
Contributor Author

He-Pin commented Aug 4, 2025

Thanks, but when I looked into the code, it gives an invokevirtual anyref#eq

@stephenamar-db
Copy link
Collaborator

I'm very skeptical that this makes a difference. Could we run some benchmarks here?

@He-Pin He-Pin marked this pull request as draft August 13, 2025 04:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants