Search Unity

How Much Do You Optimise? (quick example shown)

Discussion in 'Scripting' started by kayronjm, Aug 18, 2019.

Thread Status:
Not open for further replies.
  1. kayronjm

    kayronjm

    Joined:
    Jun 15, 2019
    Posts:
    34
    The question on the title is a bit ambiguous, so let me clarify with an example. Say you have a collider that has an OnTriggerEnter event where it sets a boolean to true and an OnTriggerExit event where it sets that boolean to false:

    Code (CSharp):
    1.     private void OnTriggerEnter(Collider collider)
    2.     {
    3.         if (colliderPivotName == "Top")
    4.         {
    5.             shipAvoidCollision.topCollision = true;
    6.         }
    7.     }
    8.  
    9.     private void OnTriggerExit(Collider collider)
    10.     {
    11.         if (colliderPivotName == "Top")
    12.         {
    13.             shipAvoidCollision.topCollision = false;
    14.         }
    15.     }
    Would you leave it like this or would you optimise by also checking if the boolean is not set to what it needs to be, such as:

    Code (CSharp):
    1.     private void OnTriggerEnter(Collider collider)
    2.     {
    3.         if (colliderPivotName == "Top" && shipAvoidCollision.topCollision == false)
    4.         {
    5.             shipAvoidCollision.topCollision = true;
    6.         }
    7.     }
    8.  
    9.     private void OnTriggerExit(Collider collider)
    10.     {
    11.         if (colliderPivotName == "Top" && shipAvoidCollision.topCollision == true)
    12.         {
    13.             shipAvoidCollision.topCollision = false;
    14.         }
    15.     }

    Do you bother with this? Is there any point in bothering doing this? Is it even more optimised code because of it? I feel like it is but maybe I'm wrong and there is just no point. I'm just wondering how meticulous to be with this when writing code. Thank you in advance for any tips! :)
     
    Last edited: Aug 18, 2019
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    It's most likely worse. If statements are actually one of the most expensive operations for the CPU because of the nature of branch prediction. That doesn't mean avoid if statements, and is completely irrelevant for 99% of code and programs so don't start mass removing conditionals from your code, but it doesn't hurt to know. Your string comparison, for example, will use thousands of more cycles than evaluating or setting a boolean ever would.

    I would also argue it makes the code less readable.
     
  3. Deleted User

    Deleted User

    Guest

    It depends on the frequency of the calls.
    If they are called rarely, you don't need to bother.

    Also there are problems with your optimized code. your if statement should be reversed. you should check for boolean first and then compare the string.
    And if you want to compare tags, you should use CompareTag method. Because tag property returns a new string.
     
    Lethn likes this.
  4. kayronjm

    kayronjm

    Joined:
    Jun 15, 2019
    Posts:
    34
    Fair enough, thank you. I'll stick to the initial idea then and try and avoid IF statements if I'm able, unless the alternative is convoluted. After all, much of a game will be based on conditions and decisions and IF statements are going to creep in naturally.
     
  5. Deleted User

    Deleted User

    Guest

    This:
    is the most important part of his answer.

    Removing if statements for optimization is pre-mature optimization. You won't need this kind of optimization for 99.9% of games.
     
  6. kayronjm

    kayronjm

    Joined:
    Jun 15, 2019
    Posts:
    34
    Got it, sounds good. Thanks! :)
     
  7. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    There's actually more to say about the example, because we don't know what all of that actually is.

    For example, if 'topCollision' were a property, and that property was known to do more work than just setting the value (e.g. raising an event or having other heavy side effects), it could actually make sense to test against the value to avoid unnecessary internal work.

    For a simple set-property or a field, in which case it would merely represent a value assignment, this is clearly a premature and unnecessary optimization. It might even cause confusion if 'topCollision' were a property, as it might suggest there's a reason that the value should not be set when the current value is that exact value. That's highly subjective though, and may depend on who you're working with.

    Also, string comparisons are not necessarily heavy operations. It can be as efficient as comparing references, but also as heavy as comparing character by character. The equality operations take all available shortcuts into account before they perform the most expensive checks.

    This being said, in general one might probably want to avoid comparing strings, but when you know that both operands are only ever going to be interned strings (e.g. strings defined as constants, or string literals), you can compare the strings without worrying about heavy equality checks. :p
     
    Antypodish likes this.
  8. kayronjm

    kayronjm

    Joined:
    Jun 15, 2019
    Posts:
    34
    Thanks for the input! :) Indeed the strings are set as-is and will not change or need any other level of comparison. As for who I'm working with, it's no issue - I'm literally a one-man-army on this project! :D
     
  9. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    Never optimize anything until you have experimental evidence this is performance problem.
     
    Kurt-Dekker likes this.
  10. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,778
    It is good to ask about writing optimal code. Even if isnt a bottle neck. This way can be learn about different and optimal solutions for particular job.

    Asking early, prevents from falling into bad habits later on.
     
  11. AndersMalmgren

    AndersMalmgren

    Joined:
    Aug 31, 2014
    Posts:
    5,358
    Use a enum instead. Much faster to compare a enum than a string. less error prone too.
     
  12. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    When writing code intially it is waste of time to care about performance. I'd rather put maximum efforts into choosing algorithm and data structures to solve task elegantly and efficiently. I would not consider where to use list or dictionary for performance reasons or check ints vs string comparsion. Just use list and compare what i have at hand. Because if I will then the elegance of solution itself won't get those efforts from me and the result will be generally worse.
     
  13. kayronjm

    kayronjm

    Joined:
    Jun 15, 2019
    Posts:
    34
    Thanks for the suggestion. I've actually done this. Now it just compares the name of the game object on the Awake stage and compares the enum value when acting on collider trigger events.
     
  14. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    This thread has such horrifying misleadingly-worded advice that's terrible for beginners so I'll try and insert some sanity for beginners:

    1. never optimise if statements, ever
    2. never optimise until your game runs sub optimally
    3. learn the built in unity profiler

    If helping beginners, orient them toward completing their projects and using the Unity profiler first.

    It's far more likely the entire technique will slow your game down long, long before if statements do.

    In fact the string compare == is the slowest part of the OP's code, followed by the magic method call of the function. So no matter what code you put inside, it's likely a) not even the bottleneck in the program b) not even something worth talking about.

    Seriously stop with the micro optimisations. Those are subjects for expert programmers working on entirely different types of code to what the OP showed, thus have absolutely no help.

    In fact with the collision methods, an if statement would dramatically speed the program up, not slow it down, because Unity only queries the results when you access them.

    The horrifying and very unhelpful "information" in this thread is so appalling I've locked it.
     
    Kurt-Dekker and Ryiah like this.
Thread Status:
Not open for further replies.