Scala 2.10, Double.isNaN, and boxing

邮差的信 提交于 2020-01-03 15:22:07

问题


In Scala 2.10, is someDouble.isNaN expected to box? Running my code calling .isNaN through a decompiler, I still see telltale calls to double2Double in my code. Given the new AnyVal work in 2.10, I'd expect it to be no worse than java.lang.Double.isNaN(someDouble) at runtime with no spurious allocations. Am I missing something?


回答1:


Unfortunately, isNaN is a method on java.lang.Double, and it is essential to have an implicit conversion to java.lang.Double, so the Scala RichDouble value class cannot reimplement isNaN to be fast, and when you use isNaN you box to java.lang.Double.

Since this leaves only slow or awkward ways to test for NaN, I define

implicit class RicherDouble(val d: Double) extends AnyVal {
  def nan = java.lang.Double.isNaN(d)
}

and then I can just use .nan to check.



来源:https://stackoverflow.com/questions/16112287/scala-2-10-double-isnan-and-boxing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!