Implicit conversion cost from java to scala collection

I would like to know the cost of an implicit conversion from a java collection to scala. There are several implicit two-way conversions in this document that say "converting from source type to target type and back will return the original source object."

I conclude that the cost should be small (wrap), but still, how much is it?

I am asking this question because I am using java sets in some scala code which is implicitly converted to scala as I import asScalaSet

(I need it in some places). However, this may be due to excessive costs for very small accessories such assize()

Somebody knows?

+3


source to share


1 answer


I decided to answer your question from a practical point of view. I used the following simple JMH benchmarks to check ops for the original scala collection and converted it (using implicit conversion).

Below is the test code:

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()
}

      

I used sbt and sbt-jmh to run. Below you will find the results:



[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, based on the results, there is actually an overhead. I will try to continue my research by explaining the reason why this is happening when I later update this question.

Please let me know if you would like me to submit the complete sbt draft for your future research.

+2


source







All Articles