从Java到Scala集合的隐式转换的成本 [英] Cost of implicit conversion from java to scala collections

查看:79
本文介绍了从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.

这篇关于从Java到Scala集合的隐式转换的成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆