C# - Simple Optimization / Variable Declaration

Between declaring a class variable then setting it in the update function, or declaring and setting a variable inside of the update function, which is better coding practice? (Assuming variable will only be used in the update function.)

public class SomeClass : MonoBehaviour {

	private float VarX;

	void Update () {
		VarX = 1f;
		...
	}
}

vs

public class SomeClass : MonoBehaviour {

	void Update () {
		float VarX = 1f;
		...
	}
}

That is, should one constantly redeclare a variable, or declare it once then only change its value, given that Update() runs so often.

If the variable value doesn't need to exist beyond the scope of the Update function then I'd say declare it there. Don't worry too much about efficiency because the compiler is going to make the better choices for you generally. You don't want to be allocating huge sums of memory every Update, don't get me wrong.. but one float isn't a big deal.

I'm more looking for a "general practice" sort of guideline, so that I don't have problems later on (when a lot of variables are being used).

Ive done some research on optimization of code and came across this website : http://www.tantalon.com/pete/cppopt/main.htm Eventhough this is meant for C++ , im pretty sure the same rules apply to every other language out there. good luck!

1 Answer

1

Thanks for the comments, I’ll mark this as answered.

If the variable value doesn’t need to exist beyond the scope of the Update function then I’d say declare it there. Don’t worry too much about efficiency because the compiler is going to make the better choices for you generally.

For general practice what @flaviusxvii said is right. There is practically no optimization, the most important thing to keep in mind is scope. …
If it’s a variable that stores a lot of information and declaring it in your Update loop requires you to repopulate that variable every frame, then consider declaring it globally and setting the information less often.