performance - Option.isEmpty 的更快实现?

标签 performance scala

isEmpty的实现在 Option很简单 - 这是一个草图:

abstract class Option[+A]           { def isEmpty:Boolean  }
object None extends Option[Nothing] { def isEmpty=true }
final class Some extends Option[+A] { def isEmpty=false }

isEmpty 被大量使用,包括在 Option 本身内部,因此它的性能很重要,即使它是如此微不足道。

我怀疑实现它会更快:
abstract class Option[+A] { final def isEmpty = this eq None  }

这个实现不需要取消引用选项或调用它的任何方法,AFAIK - 只是一个简单的引用比较。

我会对此进行性能测试,但是 JVM 微基准测试非常棘手,以至于我真的对自己创建有意义的结果的能力没有信心。

有没有我忽略的因素?

最佳答案

(基于 Eugenes Zhulenev 的评论)

HotSpot 编译器似乎会自动做这个优化,因为只有 Option 的两个子类。 :

Polymorphism Performance Mysteries Explained :

The Server HotSpot compiler, according to Cliff Click, deals with bi-morphism as a special case of poly-morphism: "Where the server compiler can prove only two classes reach a call site, it will insert a type-check and then statically call both targets (which may then further inline, etc)."

关于performance - Option.isEmpty 的更快实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28328786/

相关文章:

multithreading - 从另一个线程修改局部变量是什么意思?

java - Java 8's Optional, Scala' s Option 和 Haskell 的 Maybe 之间的主要区别是什么?

scala - 在 Spark-Streaming 和 Cassandra (Scala) 中使用 future

python - 增加对和的速度 - Codewars

php - CodeIgniter Performance 多次加载 View 与 View 循环

scala - 使用 Spark 从目录中读取多个文件

scala - 将play工程打包成jar/war文件

performance - 我如何评估我的 spark 应用程序

ios - 如何发现 OpenGL ES 帧速率是否卡顿 - 没有仪器?

c# - 提高 C# 中的速度性能