Two solutions with min max values - which should be slower? While practicing at codinbat.com on the assignment:


  Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in Math.min(v1, v2) and Math.max(v1, v2) methods return the smaller or larger of two values.


I wrote a solution (1):

public int bigDiff(int[] nums)
{
    int min = nums[0];
    int max = nums[0];    

    for (int i = 1 ; i &lt; nums.length; i++)
    {
        if (nums[i] &lt; min)
        {
            min = nums[i];
        }
        if (nums[i] &gt; max)
        {
            max = nums[i];
        }        
    }

    return max - min;  
}


You can see it has no Math.min or Math.max calls. So then I rewrote the solution to see how it looks with Math.min and Math.max:

public int bigDiff(int[] nums)
{
    int min = nums[0];
    int max = nums[0];    

    for (int i = 1 ; i &lt; nums.length; i++)
    {
        min = Math.min(nums[i],min);
        max = Math.max(nums[i],max);
    }

    return max - min;  
}


The solution became a little shorter, but I think it makes unnecessary assignments when going through the array. 

Is solution (2) in general slower than solution (1)?
To answer your question: those solutions are identical performance-wise. There is no "magic" in Min or Max methods: they do the same thing you do in your first solution - compare the two values using if operator. There is no significant performance cost for a method call or for an extra assignment - those operations are so cheap, that you won't solve any real-life performance issue with this kind of optimization. If you will become obsessed with those small things - it will have a negative effect on your code quality. So, instead of asking, which is faster, you should ask yourself which is more clean, readable and OOP-ish. I would go with second solution.

If you want to really speed things up - you should first identify the real problem. In your example - it is the number of iterations, not the number of assignments. So the faster solution would probably involve multi-threading and iterating through different parts of your array simultaneously.