- Home /
is it a unity fault or this little script done this lag?
i added to my project this code:
public static List<List<T>> GetAllCombos<T>(List<T> list)
{
int comboCount = (int)Math.Pow(2, list.Count) - 1;
List<List<T>> result = new List<List<T>>();
for (int i = 1; i < comboCount + 1; i++)
{
// make each combo here
result.Add(new List<T>());
for (int j = 0; j < list.Count; j++)
{
if ((i >> j) % 2 != 0)
result.Last().Add(list[j]);
}
}
return result;
}
before this i had a normal framerate but now in stats i have 0.1fps. Is it possible that this script made this?
Answer by tanoshimi · Jun 18, 2017 at 11:22 AM
Yes, quite likely. The Unity Profiler will confirm that for you, but this script looks like it could get horribly inefficient, horribly quickly...
What exactly are you trying to do? How often are you calling this function? How many items are there in "list"?
If there are, say, 20 items in list, and you're calling this function in Update(), then the statements inside your nested loop are being executed 20,971,520 times every frame...
it's for combinations in the list are only 4 objects but it's called in update :/
but the problem is that it's not only 0.1fps but the whole unity doesn't react, even profiler don't work
The main problem here is most likely the garbage that the method is creating. If the input list has 4 elements you get 16 combinations. Since you didn't specify a capacity for the result list it will grow automatically. This will create an array of 4, 8 and 16 elements as you go. An array of a reference type has a fix overhead of 16 bytes (4B array type ref, 4B syncblock, 4B element type ref, 4B element count var). So just the memory allocated for the result List is: 32, 48 and 80 bytes. The List class itself also has 8 bytes overhead and it's fields take up 12 bytes. So you create about 170bytes of memory just for the "result" List. By specifying a capacity you could save 70 bytes of garbage.
Each of the sub Lists require another 20 bytes for the List and 32 bytes for the array. Since there are 16 Lists it will be 52*16 == 832 bytes (though since one List is empty it doesn't have an array so -32 bytes == 800 bytes)
So just your result object tree will allocate roughly 1$$anonymous$$ of memory every frame
Ins$$anonymous$$d of $$anonymous$$ath.Pow(2, list.Count)
you should simply use (1<<list.Count)
How exactly do you use the result of your method? $$anonymous$$aybe you can avoid creating / recreating those Lists all the time?
first 24 combinations because 4! = 1*2*3*4 = 24 and i use it for ai i have like 4 enemies (it's strategical game) and i use it to decide which combination of enemies have best chances to take players point
In a strategic game, do you really need to recalculate which enemy has the best attack position every frame (i.e. 60 times a second)? Sounds like that's something that could be done maybe every half a second at most...
Your answer
