0

I was solving the below question on leetcode:

You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has.

I submitted the below 2 solutions. First using streams java 8 and the other one using normal nested for loops. Time taken for each of these was 2ms and 0 ms respectively. Does anyone know why this performance overhead?

public int maximumWealth(int[][] accounts) {
    int maxWealth = 0;
    for (int[] customer : accounts) {
        int temp = Arrays.stream(customer)
                .sum();
        maxWealth = Math.max(temp, maxWealth);
    }
    return maxWealth;
}

public int maximumWealth(int[][] accounts) {
    int maxWealth = Integer.MIN_VALUE;
    for (int i = 0; i < accounts.length; i++) {
        int temp = 0;
        for (int j = 0; j < accounts[i].length; j++) {
            temp += accounts[i][j];
        }
        maxWealth = maxWealth < temp ? temp : maxWealth;
    }
    return maxWealth;
}

TIA.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • The two implementations shouldn't be expected to perform identically. But how you're benchmarking may be a more important question for now. – ernest_k Feb 05 '21 at 19:29
  • Because streams have an overhead, that's just the way it is. Is the overhead enough to matter? It is if your profiling of the application says it is, but very likely not. – Andreas Feb 05 '21 at 20:35

0 Answers0