Introduction:
...
TypeTag[T]
encapsulates the runtime type representation of some compile-time typeT
. ...
...TypeTag
s are always generated by the compiler. ... [1]
TypeTag
s are located in scala.reflect.**
packages.
Another SO answer mentions that using java reflection will incur a run-time performance overhead in your application.
Question:
To what extent do TypeTag
s, ClassTag
s and WeakTypeTag
s use java reflection at run-time? They are generated at compile time, but do they cause a run-time performance overhead when used?
Example:
def isOfType[A : ClassTag : TypeTag, E : ClassTag : TypeTag](actual: A, expected: E): Boolean = {
actual match {
case _ : E if typeOf[A] =:= typeOf[E] => true
case _ => false
}
}
assert( isOfType(List.empty[Int], List.empty[Int]))
assert(!isOfType(List.empty[String], List.empty[Int]))
Although the tags are generated at compile-time, I can feel the delay when running it. Do the type comparisons use the not-so-performant java reflection under the hood?
Well, you can look here. In your case Java reflection is not involved, but =:=
eventually delegates to isSameType2
, which is quite non-trivial. It does check reference equality first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With