Unity Code Optimization - Do you know them all?

แชร์
ฝัง
  • เผยแพร่เมื่อ 25 ธ.ค. 2024

ความคิดเห็น • 545

  • @RobLang
    @RobLang 2 ปีที่แล้ว +406

    Interesting results! Whenever I teach optimization, I always begin with "Measure, don't guess". Measure for your platform. Measure in real world situations. Start with readable code, measure and then fix to meet a frame budget. Everything else is premature optimisation because you can't guess what optimisations the compiler will do.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +69

      I like this and fully agree.

    • @danebramage452
      @danebramage452 2 ปีที่แล้ว +2

      There's a saying... you get what you measure.

    • @saniel2748
      @saniel2748 2 ปีที่แล้ว +11

      You can pretty much always guess that arrays iteration is faster than linked list.
      And pretty much guess that GetComponent in Update is kinda bad

    • @BDCPT-NguyenThanho
      @BDCPT-NguyenThanho 2 ปีที่แล้ว

      at the example between Vector3.Distance vs SqrMagnitude have u try ((Random.insideUnitSphere - Random.insideUnitSphere) * MULTIPLIER).sqrMagnitude || i think it is a bit faster || 1 multiplier and 1 subdivisor faster than 2 multiplier and 1 subdivisor right ? (this is my opinion)

    • @beanieteamie7435
      @beanieteamie7435 ปีที่แล้ว

      In my case I'm working with a compiler that literally doesn't optimize anything, this creates code that runs several orders of magnitude slower than a regular monobehavior.

  • @r6scrubs126
    @r6scrubs126 2 ปีที่แล้ว +291

    Love to see actual tests instead of people just repeating the same things they heard elsewhere. Good job

    • @alexey6343-x0
      @alexey6343-x0 ปีที่แล้ว +1

      "Actual" means on different devices with different CPU architectures and different compiler options?

    • @ЛеняБорисов
      @ЛеняБорисов 11 หลายเดือนก่อน +2

      your clients (means gamers) are playing in unity editor? If they so, you could apply on that "tests". Anybody actually developed at least one game says that you must check optimization in release build on device only

  • @avgchoobafan
    @avgchoobafan 2 ปีที่แล้ว +59

    Really nice insight on code performace! I would recommend having an "average" result for each test in miliseconds, so the more you test you get a stable number to compare.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +23

      Damn! Why didn't I think of that. Great suggestion

  • @bonehelm
    @bonehelm 2 ปีที่แล้ว +123

    Regarding the Vector3.Distance function, you're also making 2 calls to Random.insideUnitSphere, which definitely makes 1 call to sin and 2 to cos, which are also both expensive operations. But then you're calling it twice. The 6 calls to sin/cos probably dwarf the time it takes to make 1 sqrt call. That's probably why sqrt and sqrtSquared about the same time, cause the 6 trigonometric computations are taking over.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +51

      You're right. The simplified code I posted on screen shows more predictable results, but even then... not enough for me to use the less readable option. (900k iterations, 6ms and 4ms)

    • @television1088
      @television1088 2 ปีที่แล้ว +18

      Also you should be comparing it to MIN_DIST*MIN_DIST

    • @davibergamin5943
      @davibergamin5943 2 ปีที่แล้ว +3

      @@television1088 if we cache MIN_DIST*MIN_DIST it will be the same thing

    • @television1088
      @television1088 2 ปีที่แล้ว +3

      @@davibergamin5943 That's not something that would ever be cached except for artificially improving benchmarking.

    • @vizepi69
      @vizepi69 2 ปีที่แล้ว +9

      @@Tarodev Your simplified code is still hiding the call to operator- which *may* have an impact on performances, even if Vector3 is stack-allocated, it can trigger a call instruction to operator- and constructor. By manually writing a Vector3.SqrDistance( Vector3 a, Vector3 b ) you can have a ~40% gain in performances

  • @sdhority
    @sdhority 2 ปีที่แล้ว +11

    The order of operations bit is really handy, it's really impressive to see the difference that just reorganizing your math can make on computing time. Thanks!

  • @CheeseChuckie
    @CheeseChuckie 2 ปีที่แล้ว +33

    I love a good caesh!
    Speaking of - I've heard the idea of a "Runtime Set" in a few talks regarding scriptable objects. I think it's a very nice alternative to finding objects by/of

  • @lastsipahi
    @lastsipahi ปีที่แล้ว +4

    Last one completely caught me off-guard. It'll be hard to erase a 10 year old habit! Great video btw, thx.

  • @ronygankin4158
    @ronygankin4158 2 ปีที่แล้ว +4

    Hey Tarodex, avid fan here.
    I've been studying game dev in a local college here (its unlike US colleges) and while we learned alot of game oriented programming, your more "classic" programming stuff is just enormously helpful because you stay so relevant to video game programming.
    Really wanted to thank you for that, it's super enriching and I learn alot from your videos.
    If you ever make a series that's more in depth programming then getting components while still staying relevant to video game programming. You have a fan waiting.
    Thx alot for sharing all that knowledge my friend!

  • @yerngames
    @yerngames 2 ปีที่แล้ว +25

    Great video! Just remember everyone, optimization is the last thing to do! Do not try to optimize everything that you make at the start. I always suggest to make a sloppy prototype and re-write an optimized version of whole code later on.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +10

      I cannot heart this comment enough. I was planning on adding a prefix to this video regarding pre-optimization but I guess it slipped my mind.

    • @yerngames
      @yerngames 2 ปีที่แล้ว +3

      @@Tarodev Thanks for the heart :P

    • @umapessoa6051
      @umapessoa6051 2 ปีที่แล้ว +7

      I disagree, its the same as doing multiplayer games, its something that is easier/faster/better to do since the beginning.

    • @RobLang
      @RobLang 2 ปีที่แล้ว +5

      @@umapessoa6051 I disagree. It's not the same. Multiplayer sets architectural constraints on your code, so you should do at start. Optimization should be as a result of measurement. You cannot guess what the compiler will do.

    • @umapessoa6051
      @umapessoa6051 2 ปีที่แล้ว +5

      @@RobLang when your game grow big enough its pretty hard to change the base of your code to optimize it, you'll probably lose a lot of time doing it, you can't predict what the compiler will do but you can know for sure that some functions/ways of doing things shouldn't be used at all as there's more optimized options.

  • @Iboshido
    @Iboshido 2 ปีที่แล้ว +3

    Love this type of videos. Code optimization in Unity isnt covered enough on TH-cam

  • @treppas
    @treppas 2 ปีที่แล้ว +3

    Super interesting! Thanks for taking the time to put this together and share it 😊.

  • @szyslay
    @szyslay 2 ปีที่แล้ว +7

    SUCH a gem of a video! Currently makiny my game on Early Access and this helps. Glad to use all recommended functions already ^_^ Thank you for sharing!

  • @FaDe587
    @FaDe587 2 ปีที่แล้ว +8

    Regarding the Vector Distance thing:
    It is important to note that Vector3.Distance and sqrMagnitude do NOT produce the same result.
    The result of Vector3.Distance produces the magnitude of the direction vector between the supplied vectors whereas sqrMagnitude is that same magnitude squared.
    This can be useful if you want to compare distances, e.g. to see which of two positions is further away, because you don't really care about the actual distance but rather which of the two is greater. If you however need to get the actual distance, you have to use either Vector3.Distance or magnitude, sqrMagnitude will be incorrect.

  • @odo432
    @odo432 2 ปีที่แล้ว +28

    In regards to the NonAlloc, I've done some testing with this and it can yield significant performance improvements depending on how you use it. For example, if you perform a OverlapSphere and there is 100 colliders then it will process 100 colliders. However, if you use OverlapSphereNonAlloc and set it to 10 then it will only process 10 colliders and disregard the rest. This can be handy, for example, if you want to improve performance at the cost of accuracy.
    EDIT 1: Just had a go at your WEBGL build. Using Vector.Distance is almost twice as slow for me with 900k loops (12ms for Distance vs 7ms for Square Root).
    EDIT 2: Just had a go with the order of operation. Even with 900k loops I would almost always get 6ms for each one. But every now and then FxFxV would jump to 9ms whilst the other two would stay on 6ms or jump to 7ms. For the most part, I don't think order of operation has a significant impact.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +3

      The NonAlloc collider limit is great. I use it for grounding and use an array of size 1.
      As for the results... It seems WebGL is just insanely varied from pc to pc and browser to browser. My webgl distance comes out to 6ms and 4ms, so sqrMagnitude wins, but not by enough to not use the far more readable Vector3.Distance. Order of operation comes out identical for me on both webgl and il2cpp.

    • @FaDe587
      @FaDe587 2 ปีที่แล้ว +4

      @@Tarodev I would guess that Order Of Operation might be one of those things the compiler can detect and optimize away.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      @@unitydev457 that's actually a test I'd like to run... If there's 1000 colliders and you limit it to 10, how much faster is that

  • @eduardo-silva-79
    @eduardo-silva-79 2 ปีที่แล้ว +1

    Certainly didn't know a lot of these and they are really useful! The time complexity test also helps to understand your point quite a bit more, rather than simply trusting your word.

  • @MalbersAnimations
    @MalbersAnimations 2 ปีที่แล้ว +2

    You my friend, have earned the bell notification button... well done 👏👏👏👏

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      Oh wow. Thank you ❤️

  • @FyresGames
    @FyresGames 2 ปีที่แล้ว +1

    The Linq vs For was one I was looking for. I was annoyed by a friend refactoring my for loops into Linq behind me because "Cleaner". It made my day to see that concrete proof I was right.

  • @hasankarakoc1576
    @hasankarakoc1576 2 ปีที่แล้ว +2

    I was just researching for it and you made it just in time! Thanks!

  • @okee
    @okee 2 ปีที่แล้ว +1

    Code optimization is one of the things I planned to improve this month. VERY BIG THANKS!!

  • @nodaichi6080
    @nodaichi6080 2 ปีที่แล้ว +1

    i have no idea why, but hearing your voice just makes feel soothed.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      Awwww ❤️

  • @overrideFunction
    @overrideFunction 2 ปีที่แล้ว +3

    Being new to Unity this was fantastic. It also provided some context to how expensive calls actually were. Needless to say I will avoid the game object and type find calls like crazy!

  • @t33h33studio
    @t33h33studio 4 หลายเดือนก่อน

    I always knew FindObjectOfType was on the slower side, but that is still surprisingly slow from what I was thinking. Good stuff!

  • @badscotsman
    @badscotsman 2 ปีที่แล้ว +8

    Great video! You hit on all my potential talking points concerning usage. 😊
    Another one you see a lot is using CompareTag() vs using the == operator. Speaking of, how Unity overrides the == operator is another subject worthy of a video. 😅

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +5

      Whenever I can please you, I know I've done alright 😊
      And dammit! Compare tag would have been a great one to showcase

    • @freddyspageticode
      @freddyspageticode 2 ปีที่แล้ว

      Wait so which is faster?

    • @BenVanTreese
      @BenVanTreese 2 ปีที่แล้ว +1

      @@freddyspageticodeCompareTag is much faster. As well as you should avoid object.name where you can, as it crosses C++ boundary AND allocates. (i.e. if(obj1.name == obj2.name))

    • @Handlessuck1
      @Handlessuck1 2 ปีที่แล้ว

      @@BenVanTreese Why would c++ be slower if its going to become assembly?

    • @BenVanTreese
      @BenVanTreese 2 ปีที่แล้ว

      @@Handlessuck1 It depends on what you mean, generally C++ is faster.
      Both C# (when using IL2CPP), and C++ are compiled to native instructions,
      but due to the general nature of C#, when it "talks to" the C++ portion of the engine itself, it needs to do some marshalling and etc.
      (C++ doesn't really become assembly, it is compiled to native instructions, which we write as ASM so people can read it, but ASM is just another language that is converted to actual bin instructions, which are defined by the specific arch of the CPU/target)
      This causes it to do extra work + allocate memory that needs to be GC later.
      CompareTag is optimized where it does the work in the "native" part of the engine without requiring the marshalling and etc.

  • @SlyzDev
    @SlyzDev 2 ปีที่แล้ว

    Bro. Im actually watching all your videos and they all are just too good for someone like me. Like seriously. I never comment under videos but like litteraly what you show is so damn useful lmao thanks for everything

  • @YasserSedrati
    @YasserSedrati 2 ปีที่แล้ว +2

    You did all what we was wondering about. Thanks for this video!
    -good UI scene btw.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      Better than looking at some boring numbers in a console :)

  • @zenmasters_games
    @zenmasters_games 2 ปีที่แล้ว +2

    Bro, you deserve way more subs! Cheers 🍻

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      Thanks brother

  • @Rubidev
    @Rubidev 2 ปีที่แล้ว +8

    It`s intersting that despite my thoughts that unity tuorials are saturated, you still manage to surprise us with unique videos. Very intersting level of expertise. I salute you!

  • @simoncodrington
    @simoncodrington 9 หลายเดือนก่อน +1

    Fascinating, never knew transform wasn't a direct property and that behind the scenes it was going off and doing stuff, another quick win for caching

  • @zoks
    @zoks 2 ปีที่แล้ว +1

    Release builds will have vastly different perf than what you see in the editor (debug). Great vid.

  • @VEOdev
    @VEOdev 2 ปีที่แล้ว +1

    This channel faster became my favorite game dev channel with many useful information that no other dev talking about and things I didn't really know they exist or how to use them .. I would like to see a Playfab tutorial on multiplayer game and matchmaking and stuff it will really help since there isn't any one talking about it and who talks about it only shows the basics but no one goes deep in it and there is non useful documentations

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      I did a recent one on LootLocker, but it's not a step by step tutorial, more of an overview.

  • @synchaoz
    @synchaoz 2 ปีที่แล้ว

    Dude, yes, love vids like these and you're like the only one on the planet doing them. Much love.

  • @kingreinhold9905
    @kingreinhold9905 2 ปีที่แล้ว +1

    This unity scene is so good for teaching these optimisations... Great quality content as always! Keep going, thanks for your work!

  • @Spleegness1
    @Spleegness1 2 ปีที่แล้ว +1

    God DAMN this is exactly my kinda video. You're incredible!! Thanks for the hard work

  • @TheOriginalDarkGlitch
    @TheOriginalDarkGlitch 2 ปีที่แล้ว +1

    You are doing the Lord's work. Thank you for being awesome, I always wanted to do tests like this, but I don't have time right now.

  • @XinvaderGaming
    @XinvaderGaming 2 ปีที่แล้ว

    The comnt section is very positive and downright encouraging! Love it!

  • @CrazyMan-lt6ky
    @CrazyMan-lt6ky 2 ปีที่แล้ว +2

    Man, you're rocks! Thank You for your course !!! I've learned so much!!!

  • @AndersonReis42
    @AndersonReis42 ปีที่แล้ว

    "send message is not a good practice"
    and here I was sitting and thinking i was doing a neat job using send message to optimize my code.
    thanks for the tip!

  • @zerohidz
    @zerohidz 2 ปีที่แล้ว +1

    I havent watched the video yet but I'm sure it will enhance my knowledge and benefit me. Thanks, please keep this quality content.

  • @bxbvxbv
    @bxbvxbv 2 ปีที่แล้ว +1

    finally I can focus on just writing simple working code rather than constantly stressing by thinking about ways to make it performance efficient. the amount of emphasize regarding using some functions in docs & web is too much, that if you do this then it's slower. thanks for making this awesome test 🔥

  • @jacques-dev
    @jacques-dev 2 ปีที่แล้ว

    (cries in cache) Thanks for the great video dude, I'd love to see more videos like this with more unity specific things, like nesting GameObjects vs. having them live free and wild in the hierarchy, nesting canvases, and other best practices for performance

  • @yudanaim6849
    @yudanaim6849 2 ปีที่แล้ว +2

    Awesome video. Im waiting for ECS comparison

  • @danleg1
    @danleg1 2 ปีที่แล้ว +2

    Super helpful tests, would love to see more this

  • @lee1davis1
    @lee1davis1 2 ปีที่แล้ว

    Order of operation is the only one I did not know about. Glad you added it too.

  • @DevDunkStudio
    @DevDunkStudio 2 ปีที่แล้ว +28

    This one is great to know for performance and not many use this properly:
    Caching WaitForSeconds and other yield return calls (like WaitForEndFrame etc) in a coroutine!
    You can cache the variable as private WaitForSeconds = new WaitForSeconds (1f);
    Without doing this you'll add stuff to the garbage collector every so often which can add up!
    Bonus nitpick: you can change both transform.rotation and .position by calling setPositionAndRotation, then the calls are merged into 1?

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +8

      I remember years ago when I first decompiled WaitForSeconds to discover it being a class and not a struct. I was shocked and began caching them ever since. Nice tip!
      Also yup, just decompiled setPositionAndRotation and it is indeed just one extern call.

    • @AJ213Probably
      @AJ213Probably ปีที่แล้ว +2

      Be very careful with this. You may be tempted to make central area with different cached wait for seconds. Or maybe you would make a dictionary for caching this too.
      The problem with that is if multiple coroutines are using the same wait for seconds, the timing will be completly wrong due to the internal timer being reset when the routines exit. I find this often at my job.

  • @sinisterdesign
    @sinisterdesign 2 ปีที่แล้ว +7

    Great video! It's especially good to see the StringBuilder hype confirmed. I'd love to see the performance of the string Contains() method compared to alternatives like IndexOf(), RegExp, and Linq.

  • @francoismentec4260
    @francoismentec4260 2 ปีที่แล้ว

    I LOVED this video, I just started Unity and you are my favorite channel so far.
    Quality content focused on Unity (not generic programming stuff) and Game Dev.
    I did not even knew about Unity making external call to C++
    I would be interested in a follow up video focusing on differences across platforms. Maybe look at Browser vs Windows vs Mobile.

  • @testitestmann8819
    @testitestmann8819 2 ปีที่แล้ว

    The sqrMagnitude really surprised me. I made sure to always avoid the sqrt calls. Thank for checking!

  • @cgh353
    @cgh353 2 ปีที่แล้ว +1

    this is useful. thanks. I would like to see you test optimization on more code.

  • @daniel_keen
    @daniel_keen 8 หลายเดือนก่อน

    I did not know about the order of operations. Very interesting!

  • @TheIcyGoose
    @TheIcyGoose 2 ปีที่แล้ว +6

    Thank you for an excellent video!
    I would be interested to see you run these tests in a build and not in the editor. I find the performance is usually different once you build and run.

  • @rickloyd8208
    @rickloyd8208 หลายเดือนก่อน

    Very interesting, thanks for your work and sharing results with us!

  • @svendpai
    @svendpai 2 ปีที่แล้ว +1

    been looking for a video like this, taro you champ

  • @KojiKazama
    @KojiKazama 2 ปีที่แล้ว

    Thank you sir. I will need to make a quick reference for these. The last one was unexpected as I didn't think the order actually mattered.

  • @jonathansaindon788
    @jonathansaindon788 2 ปีที่แล้ว +3

    Nice video! For order of operations, you can achieve the same result by grouping the same types in parentheses like : Vector3 stillFast = x * (a * b).

    • @Nova04550
      @Nova04550 2 ปีที่แล้ว

      Good idea

  • @divainsyoutube4254
    @divainsyoutube4254 2 ปีที่แล้ว +1

    Great video! Haven't known them all so thanks for the knowledge!
    About the cached for-loop, I'll add and say that it is faster because the non-cached version, List.Count invokes the get method on the Count property each iteration

  • @halivudestevez2
    @halivudestevez2 2 ปีที่แล้ว +1

    thank you for mythbusting! :) I am happy you've made these clear! (SqrRoot -Distance)

  • @iDerp69
    @iDerp69 2 ปีที่แล้ว

    This is great! Hope you make more of these optimization tests in the future.

  • @gamesplusjames
    @gamesplusjames 2 ปีที่แล้ว

    This is really interesting to see! I've been talking about a few of these recently so it's good to have a clear example to point to!

  • @user-uk9er5vw4c
    @user-uk9er5vw4c 11 หลายเดือนก่อน

    this is awesome, I love this kind of low level things to improve code. thanks and you're welcome to do more videos like this

  • @doismilho
    @doismilho 2 ปีที่แล้ว

    Best dev channel currently on youtube

  • @longroadgames6592
    @longroadgames6592 ปีที่แล้ว +1

    I just found your channel and I love it. Thank you!

  • @dzj3zterminator661
    @dzj3zterminator661 2 ปีที่แล้ว

    eventually it all snapped into place and I started learning how to add all the effects, titles, motion text. It was pretty cool to see my

  • @shreyanshanchlia
    @shreyanshanchlia 2 ปีที่แล้ว +9

    Would like to see interpolated string performance added in the string builder list.

  • @Warwipf
    @Warwipf 2 ปีที่แล้ว +1

    3:53 that is super surprising to me. thanks.

  • @Mecheka
    @Mecheka 2 ปีที่แล้ว +17

    Hi! Very interesting video!
    But I've got a note/doubt:
    In the LinqvsLoop part, you mentioned that FOREACH is better than FOR if you access the de "[i]" twice or more in the loop.
    Did you try benchmarking a FOR loop caching the object at the beginning of each loop? (so you access the list/array once), but then using it several times?
    Because I think that is (roughly) what FOREACH do in the background. Also, you could test this and a versión where you also cache de COUNT before the loop.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +3

      I did not test that and yes that should come out to be equal! This has actually triggered something in me... I don't cache the item nearly enough, but end up using the index multiple times. Thanks for mentioning it!

    • @hackbeam
      @hackbeam 2 ปีที่แล้ว +2

      This topic should be pinned or mentioned in the description

    • @TheHaatchoum
      @TheHaatchoum 2 ปีที่แล้ว

      I remember quite a few months ago, coming across a general "Unity C# code and garbage optimization tricks" blog somewhere. And I specificaly remember it saying that FOREACH loop was slower and somewhat generating more garbage. It also told to always cache objects that needs multiple access. (seems like the most generic thing to say)
      But I'm nowhere near the level to even figure out what's true about this.
      So seeing this video here is a real blessing. Although, he didn't say anything about For/Foreach on the garbage side.

    • @Mecheka
      @Mecheka 2 ปีที่แล้ว

      @@TheHaatchoum for and foreach loops have been suffering optimizations all these years. I heard the same thing you say really long ago (like 3+ years). I might be wrong, but I think that with the new .net the for and foreach loops are now much more efficient, specially when iterating List. On the old times I remember avoiding Lists much more than now.
      Which remembers me, @Tarodev:
      There's another performance axis on the for/foreach loops that is much more important. And that is: what you loop through?
      - Looping arrays is better than Lists (as said, on newer unity, not by much more)
      - Looping value types is *MUCH* better than reference types (classes)
      So looping int[] would be the fastests and looping List would be slowest
      In my testing, this axis (value types and arrays) is much more important than caching (avoiding multiple access), or using for loop instead of foreach.
      I've created loop heavy algorithms that generate Gameplays (wordsearch) iterating NativeArrays of structs really quickly (few milliseconds) on low end mobile devices.
      Yes foreach is technically slower, but the difference in the new .net is not that much and iterating arrays and value types is much more important.

  • @MarkRiverbank
    @MarkRiverbank 2 ปีที่แล้ว +24

    I’ve never used “SendMessage,” but I think the intent is more of a poor-man’s publisher-subscriber pattern, in which case “GetComponent” isn’t the analog. But, C# events, UnityEvents, or a custom observer pattern would probably always be a better choice. “SendMessage” is a bit unique, in that the publisher and subscriber are completely decoupled-the publisher doesn’t know if anyone received the message and the receivers don’t know who sent it. Sounds sloppy and unnecessary, but there’s a possibility the problem is our lack of imagination for when that would be useful.

    • @RamonAlonsoLopezMartinez
      @RamonAlonsoLopezMartinez 2 ปีที่แล้ว +7

      You are correct! Send message is definitely an Observer pattern not Get Component. But still crappy and slow! And unsafe!

    • @milanstevic8424
      @milanstevic8424 7 หลายเดือนก่อน

      It was just a makeshift solution that sounded good back in the early days of Unity. Nobody sane uses it, it's a dinosaur.

  • @dathus6437
    @dathus6437 2 ปีที่แล้ว +27

    If foreach is faster in your tests, that's actually because it is implemented on a different assembly which has been compiled to release mode, whereas your for loop is in build mode which is generally way slower. This is why when compiled in webgl the for loop is actually faster!

    • @lanepemberton8466
      @lanepemberton8466 2 ปีที่แล้ว +7

      I was wondering how a for loop could be slower than a foreach as well

    • @nikoart1561
      @nikoart1561 2 ปีที่แล้ว +1

      And actually foreach generate more garbage Collection

  • @jahoopyjaheepu497
    @jahoopyjaheepu497 2 ปีที่แล้ว +3

    This is a great video, and some of your results make me feel better about optimizing some of my code; it can actually make a difference!
    In regard to NonAlloc methods, I believe the Unity 2022 documentation states that they will be deprecated. Instead, something like Physics2D.Boxcast has two overload methods - one that takes an array as a parameter, like in your example, and another that takes a List - that actually grab all colliders, not just the first one. I would be curious how these perform, and especially if the List version is notably slower and/or produces any garbage.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      That's interesting... I do prefer how the NonAlloc version works as it returns a count also. Good change IMO.

  • @Fewnity
    @Fewnity 2 ปีที่แล้ว

    Great video! Thanks, I was surprised with the results!

  • @nirangasithara
    @nirangasithara 2 ปีที่แล้ว +1

    Damn !!! it's like the first day learning programming for me. Hope in few years I can understand and utilize these !!

  • @JhonatasFarias
    @JhonatasFarias 2 ปีที่แล้ว +1

    Loved it! Do more videos like this, please! Frame Debbugger... Profiller... Physics.. would be awesome♥

  • @Norbingel
    @Norbingel 2 ปีที่แล้ว +1

    I learned more than a thing or two. Thanks!

  • @animal9633
    @animal9633 2 ปีที่แล้ว

    Thanks for that last one, I've never seen that anywhere before.

  • @Nova04550
    @Nova04550 2 ปีที่แล้ว

    Super helpful!! You put so much thought into this. You are killing it.

  • @Foxyzier
    @Foxyzier 2 ปีที่แล้ว

    Really liked this format for the video

  • @torcheyegames
    @torcheyegames 2 ปีที่แล้ว +1

    Great video. Actually the newest Rider has the last bullet point covered in their editor - it will give you a hint of "expensive computation" or something like that and you can one-click to change the order of multiplication, like from V*F*F to F*F*V.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      I've quite enjoyed that new feature

  • @Devorkan
    @Devorkan 4 หลายเดือนก่อน +2

    Even a single wasted millisecond per frame is a lot though since we only get a "budget" of 16.67 milliseconds per frame in order to hit 60 FPS (and even less with VR)

  • @PvPNetwork
    @PvPNetwork 2 ปีที่แล้ว +1

    Thanks for sharing. Even if you have an idea of what is potentially better its nice to see some testing results. The small things like VxFxFx make sense if I think about it - but I doubt I would have even thought about it until you mentioned it. Remember using strings in my item tooltip , and switched over to stringbuilder - never looked back!

  • @TheKr0ckeR
    @TheKr0ckeR 2 ปีที่แล้ว +1

    wow, great video! always stressed about optimizations

  • @Betruet
    @Betruet 2 ปีที่แล้ว

    Phat info dump, thanks for putting in the effort.

  • @qwertyram4598
    @qwertyram4598 2 ปีที่แล้ว +2

    About the distance, Godot has a separate function, squareDistance, which gives you the square of the distance(as the name implies, it doesn't root the distance). The documentation says use this if you're comparing two distances, as it's faster.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      Godot has some lovely little helper functions it seems

    • @bonehelm
      @bonehelm 2 ปีที่แล้ว +1

      @@Tarodev the reason you're not seeing a difference between distance and distanceSquared is because you're also calling Random.insideUnitSphere twice. That function calls triginometric functions 3 times, so you're doing 6 trig computations. So 6 trig computations are going to dwarf the call to 1 sqrt.

  • @briankesecker
    @briankesecker 2 ปีที่แล้ว

    Great video and app to show off these things. Would like to see another video with it running outside the editor on a smattering of target platforms.

  • @GameDevCoffeeBreak
    @GameDevCoffeeBreak 2 ปีที่แล้ว +1

    Nice work, thank you a lot for this video!

  • @NicTda
    @NicTda 2 ปีที่แล้ว +1

    Very interesting, mainly confirming what I was finding online to optimize our games.
    Regarding the last point, the Order of operations, it seems to have 0 impact on WebGL build when running your benchmark, probably because it's optimized at compile time (3ms for 900k on all tests).
    Good stuff!

  •  2 ปีที่แล้ว +1

    Very nicely put video ! Good job.

  •  2 หลายเดือนก่อน +1

    I couldn't overcome all the thread performance bottleneck and issues and started coding in ECS and everything is now so smooth and performant. Still some cases are really harder to code than MonoBheaviour, but it worths when I see the performance difference. Using Burst compiler with JobSystem and run everything parallel when possible gets a lot of performance advantage. This is similar coding with C++ but you still use C#. Interesting approach but it works pretty smooth

    • @GorasGamesStudio
      @GorasGamesStudio 2 หลายเดือนก่อน +1

      I started DOTS programming too in Unity and yes the performances are wayyyyyyy better (far away) but have to learn everything again, not easy !

  • @pixelshenanigans1511
    @pixelshenanigans1511 2 ปีที่แล้ว

    Useful comparisons, thanks for the video!

  • @Frenuellcrackser33
    @Frenuellcrackser33 2 ปีที่แล้ว +1

    Awesome one !
    Great refresher :D

  • @WagnerGFX
    @WagnerGFX 2 ปีที่แล้ว +2

    Whenever i think some code could have a performance impact I do this type of test, but a lot simpler. The whole setup for benchmarking is great and I will use it in the future to test logic faster. 👍
    I just wished there was an easy way to track GC allocations too.

    • @YoutubePremiumMem
      @YoutubePremiumMem ปีที่แล้ว +1

      The profiler is decent at telling you when gc is collected and how much but it’s a bit crap at actually helping track down the culprit and so it needs a lot of drilling down to find the offender.

  • @Nullref_Arcana
    @Nullref_Arcana 2 ปีที่แล้ว +2

    Regarding FindObjctOfType, I actually made a component that I use regularily called Fetchable, which has a string id/name field and a static dictionary. Then you can do Fetchable.Fetch(idName) to find the specific object. This of course makes it a one-to-one name to object, but I find it as a really useful alternative to any Find method (assuming it's a 1-to-1, which is often the case)

  • @animeshow2833
    @animeshow2833 2 ปีที่แล้ว

    Can't wait to see your other videos.

  • @this-is-gamedev
    @this-is-gamedev 2 ปีที่แล้ว +1

    Awesome video 👍! Did not know about the order of operation ! Now, need to refactor all my code XD.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      Please don't. I just tried 900k iterations on a standalone build and they all came out even. It's so tiny to not even matter :)

  • @insidiousmaximus
    @insidiousmaximus 2 ปีที่แล้ว +1

    excellent content so glad your channel found me

  • @soverain
    @soverain 2 ปีที่แล้ว +1

    Very interesting! Edge case for SendMessage: DLL plugins. I recenttly had to implement a iOS native camera access permission plugin and the simplest solution to get communication going was to use SendMessage.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      Oh yeah? Were interfaces a no go?

  • @KrzysztofGnutek
    @KrzysztofGnutek ปีที่แล้ว +1

    For the Linq vs Loop you mention that "foreach" is faster than regular "for" when you access the array you are looping through more than once - but what if you cache the array element so you access the array only once and then access the data on the cached object and not directly on the array? :)

    • @Tarodev
      @Tarodev  ปีที่แล้ว

      Very good question. I suspect you'll find it improves performance! You should benchmark it and reply here. I'm currently in Japan so it's a little tricky

  • @kilroyyyyy90
    @kilroyyyyy90 2 ปีที่แล้ว +4

    That last one is HUGE for my game, literally just what I needed haha
    There's quite a hefty load in FixedUpdate just because of the nature of the game, but I've been doing essentially V*F*F for everything just because it makes more sense to do that in my head. But I shall change my ways :D

    • @AntonioNoack
      @AntonioNoack 2 ปีที่แล้ว +2

      and even better, don't write it like v*f*f but instead with brackets, v*(f*f), so your future self will understand what you have done 😄

  • @r1pfake521
    @r1pfake521 2 ปีที่แล้ว +1

    I read somewhere that they store objects with tags in a extra lookup, so they only have to iterate over that one instead of iterating over overy object, so it makes sense that it is much faster

  • @emrecanarabac852
    @emrecanarabac852 2 ปีที่แล้ว

    IT'S ALWAYS THE UNDERRATED VID THAT'S LEGIT! THANK YOU!

  • @arcday4281
    @arcday4281 2 ปีที่แล้ว +1

    Cool ! Everything is clearly clear !