title: Scala - Simple Mappings over Futures and Performance
body: <p>I did some performance analysis for scala <code>Future</code>s using the below snippets.</p>
  
  <pre><code>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) {}
  }
  </code></pre>
  
  <p>Consider the following <strong>trivial</strong> snippets</p>
  
  <p><strong>Snippet 1</strong></p>
  
  <pre><code>val container = new Container(ec)
  val allIntsF = container.getInts
  
  for {
    allInts &lt;- allIntsF
  } yield {
    val allIntsTransformed = allInts.map(i =&gt; 2 * i / 3)
    val allIntsFiltered = allIntsTransformed.filter(i =&gt; i &gt; 50)
    allIntsFiltered.sum / allInts.length
  }
  </code></pre>
  
  <p><strong>Snippet 2</strong></p>
  
  <pre><code>val container = new Container(ec)
  val allIntsF = container.getInts
  val allIntsTransformedF = allIntsF.map(v =&gt; v.map(i =&gt; 2 * i / 3))
  val allIntsFilteredF = allIntsTransformedF.map(v =&gt; v.filter(i =&gt; i &gt; 50))
  
  for {
    allInts &lt;- allIntsF
    allIntsTransformed &lt;- allIntsTransformedF
    allIntsFiltered &lt;- allIntsFilteredF
    // Assume that all 3 of these are needed for some calculation
  } yield {
    allIntsFiltered.sum / allInts.length
  }
  </code></pre>
  
  <p>According to the results, <strong>Snippet 1</strong> seems to be faster than the <strong>Snippet 2</strong>. It may be because of the less amount <strong>context switches</strong> compared to <strong>Snippet 2</strong>.</p>
  
  <p><strong>Measurements</strong>(Average time for 100 runs)</p>
  
  <ul>
  <li><p>With a Thread pool of 100 threads</p>
  
  <ul>
  <li>Snippet 1 - 2.3 ms</li>
  <li>Snippet 2 - 2.86 ms</li>
  </ul></li>
  <li><p>With a Thread pool of 3 threads</p>
  
  <ul>
  <li>Snippet 1 - 1.36 ms</li>
  <li>Snippet 2 - 1.8 ms</li>
  </ul></li>
  <li><p>Is this observation correct?</p></li>
  <li>What are the other interpretations/explanations that can be given to this result?</li>
  </ul>
  
  <p>Thank you.</p>