Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Introduction:

... TypeTag[T] encapsulates the runtime type representation of some compile-time type T. ...
... TypeTags are always generated by the compiler. ... [1]

TypeTags 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 TypeTags, ClassTags and WeakTypeTags 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?

like image 313
mucaho Avatar asked Apr 17 '15 23:04

mucaho


1 Answers

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.

like image 102
Alexey Romanov Avatar answered Sep 19 '22 09:09

Alexey Romanov