- Home /
Which is a faster find? (foreach) or (for-loop)
Which is faster using this code;
for (int p = 1; p <=9; p++){
GameObject.Find("Galaxies" + activeSystemM[0] + "/Stars/" + activeSystemM[1] + "/Planets/" + p + "/Ring/" + "Ring3");
}
or
Transform[] allChildren = GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren) {
if (child.name == "Ring3") {
var script3 = child.transform.gameObject.GetComponent<RingRotate>();
if (!script3) child.transform.gameObject.AddComponent("RingRotate")
}
Answer by Freaking-Pingo · Nov 02, 2013 at 08:01 PM
First of all, you could have gone far with just a simple google search instead: C# For vs. Foreach
If you are wondering about performance, you should look into replacing your GameObject.Find()
instead, and even your GetComponentsInChildren();
as these are much performance demanding than any for/foreach difference.
Well my search was different then yours so I came up empty. so are you saying replace all the find for foreach?
I mean, so you recommend using foreach since its faster then find().
It depends on unity's data structures and how methods like Find() and GetComponentsInChildren() traverse them.
If you really want to find out which is better, write both of them and time them, then use the faster one.
Answer by firemyst · May 20, 2016 at 06:21 AM
Which is faster depends on what you're iterating over. Here's a blog comparison that iterates over multiple kinds of objects, such as DataRows and custom objects, also including the performance of the While loop construct and not just the for and foreach constructs: http://cc.davelozinski.com/c-sharp/for-vs-foreach-vs-while