Why Lambda solution takes 85 ms and old ugly "for loop" only 3 ms???


  • 0
    M

    Lambda solution takes 85 ms and old for loop only 3ms? Why leed code why?
    I would expect it to be similar in terms of performance

    public class NumArray {
    
        private int[] nums;
    
        public NumArray(int[] nums) {
            this.nums = nums;
    
    //        for (int i = 1; i < nums.length; i++) {
    //            this.nums[i] = this.nums[i - 1] + this.nums[i];
    //        }
            IntStream.range(1, nums.length).forEach(
                    i -> this.nums[i] = this.nums[i - 1] + this.nums[i]
            );
        }
    
        public int sumRange(int startIdx, int endIdx) {
    
            if (startIdx == 0) {
                return nums[endIdx];
            }
    
            return nums[endIdx] - nums[startIdx - 1];
    
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.