Every “Update” when Space is not pressed, the function calls audioSoure.Stop().
Isn’t it better to check first if the sound is being played and only stop in this case?
Just inserted if(audioSource.isPlaying) after else
I would guess you’re right, but unlike the old days when you could count every clock cycle with the assembly, things are complex enough that even the best guesses turn out to be wrong. Only way to be sure is to test.
(E.g. in the old days, they said, “cache every computation to keep from redoing it”. Nowadays, memory access is slower than computation so that doesn’t always work).
As I always try to write save code, I would rather first check whether it is necessary and only then call the function.
Therefore, “if(audioSource.isPlaying)” was added to the original code to prevent the running call of Stop().
And sorry, I started at Z80 time and the efficiency of the code is rooted deep into my brain.
That is fine as long as you consider that the audio source may also check this before attempting to stop it, and it may take longer/more cycles to check if it’s running than actually just letting the audio source try to stop it. The audio source’s code is written in C++ and may be magnitudes faster to just let run, rather than do a C# check first. A bit like remembering that it is harder for the computer to divide than multiply, and therefore better to do neither (like using sqrMagnitude over magnitude) when it can be helped, or multiplying - for instance - by 0.5f rather than dividing by 2.
And after all that, I think there is no harm in defensive coding while it doesn’t affect performance. I would say calling stop all the time when it is not playing is certainly not necessary and your code is fine