- Home /
Is iterating through an array in Update() a bad idea?
I'm trying to optimize my game a bit but I think I need to get a better grasp about what is going on in my program before I can do that with this specific problem.
Right now in Start() I'm instantiating 50 enemies off screen and deactivating them. I then have another function in Update() that will activate them when necessary. My problem lies in the for loop in Update().
Is it a bad idea to iterate through an array in the Update() function? My instinct tells me yes but again I'm trying to get a better grasp about what is going on. Does the game hang while it iterates through the array to try and find the condition it's looking for? Should I be trying to come up with a better solution or am I making a fuss over nothing? I'm concerned that the framerate could take a hit or players will see stutters as my game iterates through an array during run time. I haven't noticed a performance hit myself but I only have my PC and a Galaxy S3 to test my game on, it's not really fair to assume all my players (if I have any) will be playing on a Galaxy S3.
robert explains how to test the performance.
but what you are doing sounds totally incorrect. there is no reason I can think of that you would possibly need to check EVERY FRA$$anonymous$$E that something should be active? it simply makes no sense at all.
just think of a video game. when SO$$anonymous$$ETHING HAPPENS you then make something active or not. for example, a character is blown up, so it becomes inactive. you add bullet or a new enemy .. something becomes active
it could be you totally misunderstand how active/not active is used. perhaps you should explain what you are doing in another question and someone will point out how to do it without such an approach.
Answer by robertbu · Mar 04, 2013 at 10:04 PM
Depends on the size of the array and what processing you are doing on each element. Modern computer/smart phones/tables can do an amazing amount of processing in 1/30 of a second or so. And yes, if you have a slow iteration in an array, your game can slow way down or appear to hang.
To get an idea if you have an issue with lesser hardware, put your array lookup in a loop, so you execute the lookup multiple times per frame. Then start testing to see what number cause a slowdown on your Galaxy S3...2 times, 10 time, 100 times,1000 times. If the number is low, you have a potential issue. If it is higher you are probably okay, though nothing is sure until you test it on the actual hardware.