Performance of Lerp

If you read my previous post, you know I love to try to solve problems that do not exist like for example making Vector3.Lerp faster. I thought that maybe this method would do more than just a simple lerp and that I could offload some calculations to the Start as often I use Lerp on the same two vectors just with another time value.

So I wrote my own ManualLerp.cs:


public class Lerp
{
	private float _distance;
	private Vector3 _start, _stop, _forward;
	private LerpModeType _lerpType;
	public enum LerpModeType
	{
		Linear, InOut
	}
	
    public Lerp(Vector2 start, Vector2 stop)
    {
	    _forward = (_stop - _start);
	    _distance = _forward.magnitude;
	    //_forward.Normalize();
	    _start = start;
	    _stop = stop;
    }

	public Vector3 GetPosition(float position)
	{
		return _start + (position * _forward);
	}
	
	public Vector3 GetSmoothPosition(float position)
	{
		return _start + (Mathf.SmoothStep(0, 1, position) * _forward);
	}
}
				

So you can see, this is a fairly simple Class that just calculated the magnitude and direction vector to be used later. I opted for not normalizing the vector, because it would mean an extra step in calculation later.

I felt pretty confident about my script. Surely a manual script will succeed Unitys Allrounder Implementation.

Avg
Normal Lerp1.070 ms
Manual Lerp1.404 ms

This was dissapointing. Why did my script perform worse you might ask? Well, the profile shows two mathemaical calculations, first the direction multiplied by the length, then that result added to the start vector.
Vector3.Lerp shows only a single Vector3 operation. SO clearly they have optimized the hell out of this one.

In any case, both is not slow. When iterating over 20,000 objects Vector3.Lerp managed to calculate one Lerp in about 0,0002018 ms! :) My script managed 0,0002511 ms. I mean this is a pretty optimized piece of code and it should be.

So don't do what I did. When it comes to Lerping Unity will probably be faster than anything else. And it will be more flexible.
Something like lerping from a constantly changing start vector (e.G. transform.position ;) ) would be way slower with the script I wrote.

I also tested Vector2.Lerp and Mathf.Lerp just for comparison and fun :)
Notice the non existing difference between 2D and 3D.

Avg
Normal float Lerp3.277 ms
Normal 2D Lerp4.017 ms
Normal 3D Lerp4.035 ms
Manual Lerp5.022 ms