Search code examples
c#mathtween

Prefix Decrement vs Subtract


public static float ExpoInOut(float from, float to, float time)
{
    if ((time /= .5f) < 1f)
        return Mathf.Lerp(from, to, .5f * Mathf.Pow(2f, 10f * (time - 1f)));
    return Mathf.Lerp(from, to, .5f * (-Mathf.Pow(2f, -10f * --time) + 2f));
}

The first step in both cases is to subtract 1 from time.

The second one saves that value back into time, but since it is not used again does not matter? The first could use --time or the second could use (time - 1f) and the result is the same?

The first way might even be better if not saving.

Thanks.

edit: source: http://robertpenner.com/easing/


Solution

  • Good use on --time instead of time--. You're right that --time vs time - 1f doesn't really matter (from a code perspective) if you're not saving the new value of time but from a readability perspective you should go with the more verbose one. That being said you should always strive for readability (especially if the performance impact is 0 or negligible). You may find it more readable/supportable to do something like

    public static float ExpoInOut(float from, float to, float time)
    {
        time /= 0.5f;
        time--; 
        if (time < 0f) 
            return Mathf.Lerp(from, to, .5f * Mathf.Pow(2f, 10f * time)); 
        return Mathf.Lerp(from, to, .5f * (-Mathf.Pow(2f, -10f * time) + 2f));
    }
    

    My general rule of thumb is if you're doing math/functions inside of the parameter passing section of another method, you should minimize it as best as possible, even if that means breaking it out into smaller private methods.