Unity Code Optimization - Do you know them all?

preview_player
Показать описание
Find what common Unity optomizations truly make a difference. In this video I go over a bunch of interesting optimization tips as well and give you my recommendations on each.

Keep your code running fast with as little garbage allocation as possible by learning from these important concepts.

Some topics covered:

=========

0:00 intro
0:12 SendMessage
1:22 Extern call caching
3:02 Vector3.Distance vs SqrMagnitude
4:20 Find Objects
6:44 NonAlloc
10:51 Linq vs loops
13:16 Stringbuilder
14:20 Order of operations
Рекомендации по теме
Комментарии
Автор

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.

RobLang
Автор

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

rscrubs
Автор

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.

avgchoobafan
Автор

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.

bonehelm
Автор

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 <whatever>

CheeseChuckie
Автор

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!

sdhority
Автор

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

lastsipahi
Автор

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.

odo
Автор

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.

FyresGames
Автор

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.

yerngames
Автор

Love this type of videos. Code optimization in Unity isnt covered enough on Youtube

Iboshido
Автор

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!

overrideFunction
Автор

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.

FaDe
Автор

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

treppas
Автор

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!

ronygankin
Автор

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.

eduardo-silva-
Автор

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?

DevDunkStudio
Автор

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!

szyslay
Автор

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!

dathus
Автор

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

hasankarakoc