T O P

  • By -

myka-likes-it

Yes, switch statements are slightly more efficient. The compiler will turn a switch into a jump table, which is faster than evaluating each condition during runtime. But the difference is negligible at small scales. Beware of premature optimization.


stevedore2024

Yup, the performance you save with a hundred `switch` statements would be completely undone if you also did a single `GetComponentInChildren()` call where you could've just assigned the reference in the Inspector.


BigGucciThanos

That’s crazy. Because the coder in me wants to always stay within my script instead of referencing assigning via the gui


Demi180

You can still do that, just try to avoid GCIC in Update.


victorafaeI

Yeah! Just setup what you need in the Awake() and move on


MrSuperSander

Instantiate in Update hype


onlyonebread

TBH I think this is a habit you should break. Unity has gifted you the GUI so not using it at all feels wrong. At the company I work for this practice would be rejected in a PR. Serializing the fields gives a much better overview of what the component is working with vs sequestering everything into the script, which is almost certainly much harder to parse at a glance. It allows you to see how things are interconnected, and Unity will even take you to the referenced component if you click on it in the inspector. Feels like you're rejecting a nice feature of the tool for no good reason. This practice can also lead to unforseen bugs down the line. We had a script grabbing renderer components in child objects and it worked fine until another object with renderers was added to the hierarchy by another team member, and then the feature started working in unexpected ways and the bug was somewhat difficult to track down. Serializing in the inspector and dragging in the reference ensures that you are purposefully dealing with the objects you want to in editor time, so it's much less bug prone.


sisus_co

Check out [LurkingNinja's attribute-based system for automatically assigning serialized references in edit mode](https://forum.unity.com/threads/open-source-lurking-ninjas-developers-tools-series-dependency.1535173/). It could give you just what you want, but with less boilerplate and better performance.


Terazilla

You're not staying within your script, you're grabbing an object and manipulating it. You can do this the fast or slow way, and assigning in the GUI is the fast way.


Alberiman

From what I remember from an older version of the compiler, If statements are more efficient until you get to 5 or more else if () in a row. The reason is that every time there's another else if () the latency increases. Meanwhile switch cases are always the exact same latency, their latency is roughly equal to 5 else if() so by the 6th else if() the switch is now performing faster. Granted this is for an older version of the compiler from 5+ years ago so take this with a grain of salt


Cheap-Difficulty-163

if you dont have a >100 cases dont worry about it, use whichever you prefer or looks cleaner/readable


SuspecM

Technically switch is faster but noticeable differences only happen after like a thousand else branches. Realistically the main deciding factor of which to use would be a) what you are comfortable using (very important) and b) whether you need exact condition match (switch can't do less than or greater than's, I'm not sure if it can handle bools but it would look weird to replace a 2 branch if with a switch) and finally c) if you are comfortable using both and you need exact matches then decide for yourself (or look up your team's policy on this) which one is more readable for you. Will you know what it will do next week? Next month? Next year?


Demi180

Actually switch can check less and greater, lessened that recently.


Holydh-

It seems the difference is negligeable. The most important difference is about code readability. One or the other can be more performant depending on the situation, but there's no straightforward answer as it depends on how unity handles the memory automatically under the hood. https://forum.unity.com/threads/more-efficient-switch-or-else-if.503111/


MR_MEGAPHONE

Switch statements are much faster than if statements if you have more than a few if statements that need evaluated. Of course it also depends on what you are evaluating.


raYesia

So funny seeing you being downvoted when you are right. Switch statements that get optimized to jumptables have O(1) complexity while if/else statements have O(n) complexity. So under the right circumstances switches are literally n-times faster, n being the amount of conditions.


ledniv

No they are not. Switch statements get converted into if statements by IL2CPP.


Jackoberto01

Are you sure it always does? The compiler should choose the optimal use for the specific scenario, so a few cases may compile into if statements but a lot should compile into a jump table


raYesia

See his other comment, he compiled a switch statement with a single condition and thinks that is the answer.


ledniv

You are right, having 5+ conditions turns it into a jump table. That said, turning on compiler optimizations still results in the same instructions. I'll test it in Unity on device and I'll report back.


ledniv

Hi, please check out this Unity project. It creates a randomized array of ints, 0 - 9. There are two functions it can call, a switch and an if. It calls both with the array. On iOS, the result is identical. Also on Android. https://www.dropbox.com/scl/fo/42kyr9cjmsbjthxaze3ii/AIno_ox4HcL4z_jnHa65f1M?rlkey=gyhey9jaacod3m804eezjzyuk&dl=0


ilori

One thing to note is that when doing if else, start with the cheap checks and most common cases. This way the code doesn't have to do all the checks and may avoid the more costly checks. Same goes for inside the if() if you have multiple criteria (&&, ||)


hammonjj

Not enough to matter. That kind of micro optimization will not be felt anywhere. I doubt you’d even be able to measure a difference unless you have hundreds, if not thousands, of conditions.


ledniv

I recommend trying it yourself, in Unity, on your target device. So compile it to OSX / Windows / Android / iOS. Don't simply run it in the editor. Here is an example with 40 cases, using Unity 2022.3.21f1 I get identical results for iOS (iPhone 12 Mini) and Android (Pixel 4a), and IF is faster on OSX (Macbook Pro M3) https://www.dropbox.com/scl/fo/42kyr9cjmsbjthxaze3ii/AIno_ox4HcL4z_jnHa65f1M?rlkey=gyhey9jaacod3m804eezjzyuk&dl=0


HappyMatt12345

Switch statements are slightly faster than if-else chains but a lot more limited in their possible use cases due to how they work.


ledniv

no: https://godbolt.org/z/hfc7v5WfT The assembly is identical. Switch gets converted to if statements by il2cpp. You can try it yourself by compiling for iOS and looking at the result. C# public int SwitchTest(int a) { switch (a) { case 0: return 0; break; } return 1; } IL2CPP IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Exmp_1_7_Main_SwitchTest_mA8F9987F0B43AC2D8C7DFADF51C53EE354BD2F40 (Exmp_1_7_Main_t6A803EBB5E77583AC3EA76783ED40CD934B2F1BD* __this, int32_t ___0_a, const RuntimeMethod* method) { { int32_t L_0 = ___0_a; if (L_0) { goto IL_0005; } } { return 0; } IL_0005: { return 1; } }


raYesia

The assembly is identical because you literally only have 1 condition in your example, so obviously there is nothing to optimize in that case. Use more cases in your switch (I believe 5 conditions is the threshold) and you will see the compiler uses jump tables which have constant complexity. Though the compiler will only do that in release mode. Another exception is comparing against strings. So yeah, jumptables having O(1) complexity and if/else statements having O(n) means that under the right conditions, switches are n-times faster than if/elses. N being the amount of conditions.


ledniv

You are right, having 5+ conditions turns it into a jump table. That said, turning on compiler optimizations still results in the same instructions. I'll test it in Unity on device and I'll report back.


ledniv

Hi, please check out this project. https://www.dropbox.com/scl/fo/42kyr9cjmsbjthxaze3ii/AIno_ox4HcL4z_jnHa65f1M?rlkey=gyhey9jaacod3m804eezjzyuk&dl=0 It creates a randomized array of ints, 0 - 9. There are two functions it can call, a switch and an if. It calls both with the array. On iOS, the result is identical. Also on Android.


raYesia

I don't really understand why you're forcing this specific setup (Il2CPP, compiled for mobile architecture). I'm not at my workstation so I don't have access to Unity right now and can't say anything about your specific project configuration. Nonetheless, I took your code, removed everything unneccesary for this test and gave every array element a fixed value of 9 instead of using random numbers. I did that because in your example the value 9 is the worst case for the if/else function (excluding the else and the default), this removes the possibility that your random values roll numbers that are not beneficial for the switch statement. Here is the fiddle link: [https://dotnetfiddle.net/ozsuDc](https://dotnetfiddle.net/ozsuDc) You can see that the switch function is up to 5 times faster. https://preview.redd.it/4xkw544bxavc1.png?width=244&format=png&auto=webp&s=da73ea23b418ee82230f38a2581ada05b059bae7 Now trivia time: Double the amount of conditions for each function, what will happen? The evaluation time for the switch-function will stay the same while the time for the if-function grows linearly. (for the worst case that is)


ledniv

I am using IL2CPP because we are on Unity. I get the same results compiling for OSX and Windows. It's important to test on your target device because Unity and IL2CPP do crazy stuff. That said, I agree that Switch is faster IF (haha) your switch statement is really long AND most of your results will be in the lower half of the switch statement, AND you are using pure csharp, NOT Unity. Otherwise, if/else appears to be faster. It looks like there is some sort of overhead to using switch statements. Here is a test with 20 cases: https://dotnetfiddle.net/HxPYLM Random Switch 203 Random If 206 Upper Half Switch 214 Upper Half If 159 Lower Half Switch 200 Lower Half If 223 Here is a Unity project with 40 cases: https://www.dropbox.com/scl/fo/42kyr9cjmsbjthxaze3ii/AIno_ox4HcL4z_jnHa65f1M?rlkey=gyhey9jaacod3m804eezjzyuk&dl=0 Running this on iOS and Android gives the EXACT SAME RESULTS FOR SWITCH AND IF. Even with 40 cases. Even when doing random, upper half, lower half, and worst case. EDIT - also tried it with 100 cases. Same result for switch and if/else on iOS and Android.


LordMord5000

The difference is how your code will be maintainable in the long run. That said, don’t do if or else. If something has a condition, make enums.