title: Is Arrays.stream(array_name).sum() slower than iterative approach?
body: <p>I was coding a leetcode problem : <a href="https://oj.leetcode.com/problems/gas-station/" rel="noreferrer">https://oj.leetcode.com/problems/gas-station/</a> using Java 8.</p>
  
  <p>My solution got TLE when I used <code>Arrays.stream(integer_array).sum()</code> to compute sum while the same solution got accepted using iteration to calculate the sum of elements in array. The best possible time complexity for this problem is O(n) and I am surprised to get TLE when using streaming API's from Java 8. I have implemented the solution in O(n) only.</p>
  
  <pre><code>import java.util.Arrays;
  
  public class GasStation {
      public int canCompleteCircuit(int[] gas, int[] cost) {
          int start = 0, i = 0, runningCost = 0, totalGas = 0, totalCost = 0; 
          totalGas = Arrays.stream(gas).sum();
          totalCost = Arrays.stream(cost).sum();
  
          // for (int item : gas) totalGas += item;
          // for (int item : cost) totalCost += item;
  
          if (totalGas &lt; totalCost)
              return -1;
  
          while (start &gt; i || (start == 0 &amp;&amp; i &lt; gas.length)) {
              runningCost += gas[i];
              if (runningCost &gt;= cost[i]) {
                  runningCost -= cost[i++];
              } else {
                  runningCost -= gas[i];
                  if (--start &lt; 0)
                      start = gas.length - 1;
                  runningCost += (gas[start] - cost[start]);
              }
          }
          return start;
      }
  
      public static void main(String[] args) {
          GasStation sol = new GasStation();
          int[] gas = new int[] { 10, 5, 7, 14, 9 };
          int[] cost = new int[] { 8, 5, 14, 3, 1 };
          System.out.println(sol.canCompleteCircuit(gas, cost));
  
          gas = new int[] { 10 };
          cost = new int[] { 8 };
          System.out.println(sol.canCompleteCircuit(gas, cost));
      }
  }
  </code></pre>
  
  <p>The solution gets <strong>accepted</strong> when, 
  I comment the following two lines: (calculating sum using streaming)</p>
  
  <pre><code>totalGas = Arrays.stream(gas).sum();
  totalCost = Arrays.stream(cost).sum();
  </code></pre>
  
  <p>and uncomment the following two lines (calculating sum using iteration):</p>
  
  <pre><code>//for (int item : gas) totalGas += item;
  //for (int item : cost) totalCost += item;
  </code></pre>
  
  <p>Now the solution gets accepted. Why <strong>streaming API in Java 8</strong> is slower for <strong>large input than iteration for primitives</strong>? </p>