Switch vs If statement

Hi guys

Working on a sports sim game and seeing if the following code below would be better written as a switch statement

if (ServePassDifference == -19) 
		{
			// Calculate the random value between (and including) 1-100
			randomServe = UnityEngine.Random.Range(1,101);
			print(randomServe);
			
			if (randomServe >= ServePassm19[0])
			{
				//3 pass
				print("3 pass");
			}
			
			if (randomServe < ServePassm19[0]  randomServe >= ServePassm19[1])
			{
				//2 pass
				print("2 pass");
			}
			
			if (randomServe < ServePassm19[1]  randomServe >= ServePassm19[2])
			{
				//1 pass
				print("1 pass");
			}
			
			if (randomServe < ServePassm19[2]  randomServe >= ServePassm19[3])
			{
				//0 pass
				print("0 pass");
			}
			
			if (randomServe < ServePassm19[3])
			{
				//Ace
				print("Ace");
			}
			
		}

Wondering if there would be any performance advantages to using switch statements over if statements as Im predicting there will be close to 100 of similar calculations in the match simulation and dont know if i can get some performance upgrade through using switch statements instead

Thanks!

It’s the same)

But if you will use if… else if … else… maybe you will got some performance advantages.

Switch is just more neat also. Not much difference.

Although in a switch you can return

Switch works best when it’s just equal to something. Yours is mostly between two values, so not a very good fit. Switch works great for a state machine type application.

No, switch/case is slightly more efficient. However it can’t be used in this case, since case is only for checking single values, not ranges.

–Eric

3 Likes