Is GameObject.FindObjectOfType() less expensive in performance than GameObject.Find() in Unity? - unity3d

I'm on my last finishing touches with my indie game using Unity and I've been thinking about improving my game's performance. I was wondering if GameObject.FindObjectOfType() is less expensive than GameObject.Find()? Thanks!

If you really care about performance, try using none of them - or at least minimise it.
Using these Methods will loop through the list of GameObjects and return the object and because of the looping it is pretty heavy on the performance. So if you use them, never call them in the Update()-Method, call them in Start() or any method that doesn't get called often and store the value.
To be honest I don't know, which one is faster. If I had to guess, I would say it is GameObject.Find(), since it's only checking the name, whereas FindObjectOfType() checks the components.
But even if I would consider using FindObjectOfType(), because Find() uses a string and you might want to avoid that, because of typos (if you are not storing it inside a single class and just reference the variable)

Related

Which one is more performant : using Swift Array.contains function OR checking with if (.. || .. || .. )?

In our Swift code we're often writing this when we want to check if foo is a particular value :
if [kConstantOne, kConstant2, kConstant3].contains(foo) {...}
I was wondering how this compared, performance wise, to a normal if statement where you compare the values with ||.
if kConstantOne == foo || kConstant2 == foo || kConstant3 == foo {...}
Does the compiler optimises this statement or is an array effectively allocated, instantiated and looped to check for equality?
It's an easier, a bit more fancy way to write these simple if statements, but if there would be a significant performance impact, which I seriously doubt it will, we should try to avoid it.
EDIT : A single isolated use of this would not have any impact, but I'm more interested to know what happens when it would be part of a larger algorithm. What happens when your code is hitting this statement or other similar ones a few thousand times, allocating and initialising an array and using the contains function for equality checking.
If you are concerned about the performance impact, the only way to explore this is to benchmark it in code that you believe would cause the performance impact. While we can do some reasoning about current compiler implementation details, this is no way to translate those into answering questions of "significant performance impact" and in many cases your intuition will be wrong (map is very slightly faster than a simple for loop in most cases, which is counter-intuitive until you read the implementation of map; but it's a very tiny difference).
Write the code clearly to say what you mean. The first does that.
It is possible that the if statement is very slightly faster than the contains and allows some compiler optimizations (that may or may not actually occur) that contains does not. It definitely does not create a temporary array or anything like that. However, this is going to be nearly unmeasurable over such a tiny array either way. If this is part of an inner loop that is called a few tens of millions of times, I have some approaches I would explore to optimize it (which wouldn't look like either of these; I'd focus first on getting rid of the == if these aren't integers). If this is called fewer than a million times, then you're more likely to accidentally hurt performance than help it by micro-optimizing like this. You're definitely likely to hurt maintainability.

swift array 'contains' function in place optimization

I am wondering if the built-in array structure for the contains function has any optimizations. If it does a linear search of contains every time I run it, it's at best O(n), which turns into O(n^2) because I'll be looping through another set of points to check against, however if it somehow behind the scenes sorts the array the first time 'contains' is run, then every subsequent 'contains' would be O(log(n)).
I have an array that gradually gets larger the more in depth the user gets into the application, and I am using the 'contains' a lot, so I am expecting it to slow down the application the longer the user is using the application.
If the array doesn't have any behind the scenes optimizations, then ought I build my own? (e.g. quicksort, and do an insert(newElement:, at:) every time I add to the array?)
Specifically, I'm using
[CGPoint],
CGPointArrayVariable.contains(newCGPoint) // run 100s - 10000s of times ideally every frame, (but realistically probably every second)
and when I add new CGPoints I'm using
CGPointArrayVariable += newCGPointSet.
So, the question: Am I ok continuing to use the built in .contains function (will it be fast enough?) or should I build my own structure optimizing for the contains, and keeping the array sorted? (maybe an insertion sort would be better to use opposed to a quicksort, if that's the direction recommended)
Doing something like that every frame will be VERY inefficient.
I would suggest re-thinking your design to avoid tracking that amount of information for every frame.
If it's absolutely necessary, building your own Type that uses a Dictionary rather than an Array should be more efficient.
Also, if it works with your use case using a Setmight be the best option.

Storing object pointers efficiently for game c++

I'm making a hooked modding code for GTA San Andreas. The game has its own classes, one of them is class CPed. It handles the attributes of random pedestrians created by the game, which is huge in storage. I work with pointers to these objects in my code CPed*. Right now I use vector<CPed*> myList; to work with these objects/peds.
What is the most efficient way to store these into a container for further use? The game, itself, handles the destruction of these objects.
std::vector should actually be enough for the most part. In general, when picking a container, you should think about operations you want to do with it, but vector is almost always a good start.
If you need key-value lookup, then std::unordered_map/std::map could be of use as well.
If you need absolutely top performance, you need to benchmark different containers yourself. Using std:: algorithms and range-for should guarantee easy replacement.

Class design for weapons in a game?

I enjoy making games and now for the first time try myself out on mobile devices. There, performance is of course a much bigger issue than on a nice PC and I find myself particularly struggling with weapon (or rather projectile) class design.
They need to be updated a lot, get destroyed/created a lot and generally require much updating.
At the moment I do it the obvious way, I create a projectile object each time I fire and destroy it on impact. Every frame all active projectiles get checked for collision with other objects.
Both steps seem like they could definitely need improvement. Are there common ways on how to handle such objects effectively?
In general I am looking for advice on how to do clean and performant class design, my googling skills were weak on this one so far.
I will gladly take any advice on this subject.
When you have lots of objects being created and destroyed in a short timespan, a common approach is to have a pool of instances already allocated that you simply reinitialise. Only if the pool is empty do you allocate new instances. Apple do this with MapKit and table views, among others. Studying those interfaces will probably serve you well.
I don't think this is about class design. Your classes are fine; it's the algorithms that need work.
They need to be updated a lot, get destroyed/created a lot and generally require much updating.
Instead of destroying every projectile, consider putting it into a dead projectile list. Then, when you need to create a new one, instead of allocating a fresh object, pull one from the the dead-list and reinitialise it. This is often quicker as you save on memory management calls.
As for updating, you need to update everything that changes - there's no way around that really.
Every frame all active projectiles get checked for collision with other objects.
Firstly - if you check every object against every other then each pair of objects gets compared twice. You can get away with half that number of checks by only comparing the objects that come later in the update list.
#Bad
for obj1 in all_objects:
for obj2 in all_objects:
if obj1 hit obj2:
resolve_collision
#Good
for obj1 in all_objects:
for obj2 in all_objects_after_obj1:
if obj1 hit obj2:
resolve_collision
How to implement 'all_objects_after_obj1' is language specific, but if you have an array or other random access structure holding your objects, you can just start the indexing from 1 after obj1.
Secondly, the hit check itself can be slow. Make sure you're not performing complex mathematics to check the collision when a simpler option would do. And if the world is big, a spatial database scheme can help, eg. a grid map or quadtree, to cut down the number of objects to check potential collisions against. But that is often awkward and a lot of work for little gain in a small game.
Both steps seem like they could definitely need improvement.
They only 'seem'? Profile the app and see where the slow parts are. It's rarely a good idea to guess at performance, because modern languages and hardware can be surprising.
As Jim wrote you can create a pool of objects and manage them. If you looking a specific design pattern there is Flyweight .Hope it will help you.

Cocoa Touch Programming. KVO/KVC in the inner loop is super slow. How do I speed things up?

I've become a huge fan of KVO/KVC. I love the way it keeps my MVC architecture clean. However I am not in love with the huge performance hit I incur when I use KVO within the inner rendering loop of the 3D rendering app I'm designing where messages will fire at 60 times per second for each object under observation - potentially hundreds.
What are the tips and tricks for speeding up KVO? Specifically, I am observing a scalar value - not an object - so perhaps the wrapping/unwrapping is killing me. I am also setting up and tearing down observation
[foo addObserver:bar forKeyPath:#"fooKey" options:0 context:NULL];
[foo removeObserver:bar forKeyPath:#"fooKey"];
within the inner loop. Perhaps I'm taking a hit for that.
I really, really, want to keep the huge flexibility KVO provides me. Any speed freaks out there who can lend a hand?
Cheers,
Doug
Objective-C's message dispatch and other features are tuned and pretty fast for what they provide, but they still don't approach the potential of tuned C for computational tasks:
NSNumber *a = [NSNumber numberWithIntegerValue:(b.integerValue + c.integerValue)];
is way slower than:
NSInteger a = b + c;
and nobody actually does math on objects in Objective-C for that reason (well that and the syntax is awful).
The power of Objective-C is that you have a nice expressive message based object system where you can throw away the expensive bits and use pure C when you need to. KVO is one of the expensive bits. I love KVO, I use it all the time. It is computationally expensive, especially when you have lots of observed objects.
An inner loop is that small bit of code you run over and over, anything thing there will be done over and over. It is the place where you should be eliminating OOP features if need be, where you should not be allocating memory, where you should be considering replacing method calls with static inline functions. Even if you somehow manage to get acceptable performance in your rendering loop, it will be much lower performance than if you got all that expensive notification and dispatch logic out of there.
If you really want to try to keep it going with KVO here are a few things you can try to make things go faster:
Switch from automatic to manual KVO in your objects. This may allow you to reduce spurious notifications
Aggregate updates: If your intermediate values over some time interval are not relevant, and you can defer for some amount of time (like the next animation frame) don't post the change, mark that the change needs to posted and wait for a the relevent timer to go off, you might get to avoid a bunch of short lived intermediary updates. You might also use some sort of proxy to aggregate related changes between multiple objects.
Merge observable properties: If you have a large number of properties in one type of object that might change you may be better off making a single "hasChanges" property observe and having the the observer query the properties.