Cestarian said:
Why? I'd have thought that it's better to initialize the variable only once (e.g. in the class or in Start()) for performance reasons
Assignment of a variable is exactly the same thing as initialization for a computer, you give the variable a value. It's perfectly fine if you initialize a local variable by the value it should have anyway:
You changed the code, but in the version above my first reply, you could have written
float axisX = Input.GetAxis ("Mouse X");
Cestarian said:
Clean code is good and all but not if performance suffers for it (if you choose human readability over performance consistently it'll add up pretty fast after all).
Your ideas don't match with reality here.
Performance is important, but small fish like an assignment to a float is not going to have noticeable impact at all, not in the last place because the C# compiler removes such inefficiencies for you. (In other words, while you wrote the code, the computer never performed it because it deduced it wasn't needed for the result.)
Even if the C# compiler would not remove those, you're talking about a few nano-seconds gain at most for an eliminated assignment, good luck with that if you need to improve performance a few 1/10th of second. (To give an idea, assume 10 nano-seconds gain for 1 eliminated assignment, so for 1/10th of a second performance gain you need thus to remove 1.000.000.000 / 10 / 10 = 10.000.000 assignments. I have been programming for 50+ years and have never written a program with 10 million lines of code. Now imagine you need to improve by 30 minutes or an hour or more.
You win the war on performance by understanding how the code behaves while it is being executed. Together with benchmarking tools you can then find the troublesome spot, and fix things locally there. The key here is **understanding**. Without it you're just wandering aimlessly and you'll never hit the right spot and have an impact.
This is why human readability is the primary aim. If you can't easily read the code it becomes impossible to grasp how it works because your entire mind is bogged down into deciding what each statement is doing rather than seeing the big picture of how the code works. It's like trying to find a path on a map from town A to town B, except you're reading the map at 1 cm distance so you never see more than 1-2 streets at the same time. It becomes impossible to obtain a general direction of the path or even find which towns you generally pass through. All the high level information that you need for understanding drowns in the (almost) infinite number of street names that you see.
So aim for human readability, and don't worry much about performance until you find it is needed. Understanding the code is key so you can look at the map at a comfortable distance, intuitively understand the code, and find a good path.