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/