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?
Scala 2.10, Double.isNaN, and boxing
Asked Answered
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.
Why should this be any faster than boxing the double? –
Curium
@Curium - Because this "boxes" to a value class (that's the
extends AnyVal
part), which isn't actually created unless you need to pass it as an object or generic or put it in an array. If you just use it (like you are here), Scala emits bytecode that is just a method call, since there's actually nothing that requires a real object to exist. –
Three Couldn't there be a higher-priority implicit to your
RicherDouble
, with the same isNaN
name on it? Or if not, something of the same priority to fail with ambiguity to remind yourself not to use that method in tight loops. –
Zaragoza @MyseriousDan - I do actually define the
isNaN
method also to get an ambiguous implicit conversion warning. As for making it higher priority, you can't do that without changing the library, and I'm not sure whether the necessary change would break anything. –
Three @RexKerr Nice. Missed the
AnyVal
there. –
Curium @RexKerr do you have any particular possible breakage in mind? I could fix this with an additional layer of predef pastry. –
Fetich
@extempore - I don't, I'm just extremely wary of moving priorities around in something so incredibly heavily used. –
Three
© 2022 - 2024 — McMap. All rights reserved.