简体   繁体   中英

Scala - Run-time performance of TypeTags, ClassTags and WeakTypeTags

Introduction :

... TypeTag[T] encapsulates the runtime type representation of some compile-time type T . ...
... 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM