Object drag positioning code

I have some very simple code in my project that allows me to drag objects around the screen (2D) with the mouse:

Vector3 point;

void OnMouseDrag()
{
	point = Camera.main.ScreenToWorldPoint (Input.mousePosition);
	point.z = myTransform.position.z;
	myTransform.position = point;
}

Note that ‘myTransform’ is this gameobject’s cached transform. I added this a while ago and it works perfectly fine. I’m finishing up my project now and going back through to optimize code, and took another look at this and realized that it’s doing something I hadn’t initially realized. Because OnMouseDrag() is being called every frame, the code is actually bouncing the z position of my ‘point’ variable back and forth between the mouse’s z position and this object’s z position every single frame, which is unnecessary. I know that’s not necessarily performance intensive, but it bugs me knowing that it’s happening in my code and might be eating up tiny amounts of precious cycles.

I can see some obvious ways to fix it, but I’m honestly not sure if they’re any more efficient. For example, I could use 2 Vector3’s instead:

Vector3 point;
Vector3 pointTwo;
        
void OnMouseDrag()
{
    point = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    pointTwo = new Vector3 (point.x, point.y, myTransform.position.z);
    myTransform.position = pointTwo;
}

So now I’m not bouncing the z position of either variable back and forth, but I’m creating a new Vector3 every single frame which seems even worse.

Am I overthinking this? Would you consider my original code inefficient because of that z coordinate?

I think you are spending time on something that absolutely will not matter. What jumps out at me here is that you are not taking into account the offset between the object and the mouse, so the object will jump when you click on it.

but I’m creating a new Vector3 every
single frame which seems even worse.

Vector3 is a value type. You will not be ‘creating’ one each frame. But you could move:

Vector3 point;

…into the function. That would shrink the memory footprint of the class slightly since the variable would then be allocated on the stack.

Because OnMouseDrag() is being called
every frame

OnMouseDrag() is only called every frame while the mouse is down, not every frame while the app is running.