Scala - Simple Futures-Performance Comparisons

I did some performance analysis for scala Futureusing the snippets below.

class Container(ec: ExecutionContext) {

  implicit val executionContext = ec

  def getInts: Future[Vector[Int]] = {
    Future {
      (1 to 100).toVector
    }
  }
}

implicit val ec = new ExecutionContext {
  val threadPool = Executors.newFixedThreadPool(100)
  // val threadPool = Executors.newFixedThreadPool(2)
  // I tried with both of the above threadPools

  def execute(runnable: Runnable) {
    threadPool.submit(runnable)
  }

  def reportFailure(t: Throwable) {}
}

Consider the following trivial fragments

Fragment 1

val container = new Container(ec)
val allIntsF = container.getInts

for {
  allInts <- allIntsF
} yield {
  val allIntsTransformed = allInts.map(i => 2 * i / 3)
  val allIntsFiltered = allIntsTransformed.filter(i => i > 50)
  allIntsFiltered.sum / allInts.length
}

Fragment 2

val container = new Container(ec)
val allIntsF = container.getInts
val allIntsTransformedF = allIntsF.map(v => v.map(i => 2 * i / 3))
val allIntsFilteredF = allIntsTransformedF.map(v => v.filter(i => i > 50))

for {
  allInts <- allIntsF
  allIntsTransformed <- allIntsTransformedF
  allIntsFiltered <- allIntsFilteredF
  // Assume that all 3 of these are needed for some calculation
} yield {
  allIntsFiltered.sum / allInts.length
}

According to the results, Snippet 1 seems faster than Snippet 2 . This may be due to fewer context switches.compared to Snippet 2 .

Measurements (average time per 100 runs)

  • With a thread pool of 100 threads

    • Fragment 1 - 2.3 ms
    • Fragment 2 - 2.86 ms
  • With a thread pool of 3 threads

    • Fragment 1 - 1.36 ms
    • Fragment 2 - 1.8 ms
  • Is this observation correct?

  • /, ?

.

+4

Source: https://habr.com/ru/post/1669771/


All Articles