从Java到Scala集合的隐式转换的成本
我想知道从Java集合到scala集合的隐式转换的成本。在此文档中,有几个隐式双向转换,据说从源类型转换为目标类型然后再次返回将返回原始源对象。。
I'd like to know the cost of implicit conversion from java collection to scala ones. In this doc there are several implicit two-way conversions for which it is said that "converting from a source type to a target type and back again will return the original source object".
我得出的结论是成本应该是较小的(包装),但仍然是多少?
I conclude that the cost should be minor (wrapping), but still how much is it?
我问这个问题是因为我在某些scala中使用了java集代码,当我导入 asScalaSet
时隐式转换为scala集(在某些地方确实需要它)。但是,对于很少的访问器(例如 size()
I ask this question because I use java sets in some scala code, which is implicitly converted to scala set as I import asScalaSet
(I do need it in some places). However, it might be a consequent overhead for very little accessors such as size()
这样的访问者,可能会产生开销),有人知道吗? / p>
Does anyone know?
我决定从实际角度回答您的问题。我使用以下简单的JMH基准测试原始scala集合的每秒操作,并转换了一次(使用隐式转换)。
I decided to answer your question from practical point of view. I used the following simple JMH benchmarks to test operations per second for original scala collection and converted one (using implicit conversion).
请在下面找到基准代码:
Please find below code of benchmark:
import org.openjdk.jmh.annotations._
import scala.collection.JavaConversions._
@State(Scope.Thread)
class WrapperBenchmark {
val unwrappedCollection = (1 to 100).toSet
val wrappedCollection: java.util.Set[Int] = (1 to 100).toSet[Int]
@Benchmark
def measureUnwrapped: Int = unwrappedCollection.size
@Benchmark
def measureWrapped: Int = wrappedCollection.size()
}
我使用了sbt和sbt-jmh运行插件。请在下面找到结果:
I used sbt and sbt-jmh plugin for running. Please find results below:
[info] Benchmark Mode Cnt Score Error Units
[info] WrapperBenchmark.measureUnwrapped thrpt 200 353214968.844 ± 1534779.932 ops/s
[info] WrapperBenchmark.measureWrapped thrpt 200 284669396.241 ± 4223983.126 ops/s
因此,基本上根据结果,确实存在开销。在以后对该问题的更新中,我将尝试继续进行研究,并提供其原因。
So basically according to results, there is overhead indeed. I will try to continue my research providing the reason why it is like this in later update to this question.
请让我知道是否要共享完整的sbt项目为您的未来研究。
Please let me know if you want me to share complete sbt project for your future research.