简体   繁体   English

Scala - TypeTags,ClassTags和WeakTypeTags的运行时性能

[英]Scala - Run-time performance of TypeTags, ClassTags and WeakTypeTags

Introduction : 简介

... TypeTag[T] encapsulates the runtime type representation of some compile-time type T . ... TypeTag[T]封装了某些编译时类型T的运行时类型表示。 ... ...
... TypeTag s are always generated by the compiler. ... TypeTag总是由编译器生成。 ... [1] ...... [1]

TypeTag s are located in scala.reflect.** packages. TypeTag位于scala.reflect.**包中。 Another SO answer mentions that using java reflection will incur a run-time performance overhead in your application. 另一个SO回答提到使用java反射会在应用程序中产生运行时性能开销。

Question : 问题
To what extent do TypeTag s, ClassTag s and WeakTypeTag s use java reflection at run-time? TypeTagClassTagWeakTypeTag在运行时使用java反射的程度如何? 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? 类型比较是否使用了引擎盖下不那么高效的java反射?

Well, you can look here . 好吧,你可以看看这里 In your case Java reflection is not involved, but =:= eventually delegates to isSameType2 , which is quite non-trivial. 在你的情况下,不涉及Java反射,但是=:=最终委托给isSameType2 ,这非常重要。 It does check reference equality first. 它首先检查参考平等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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