So, I have a natural selection simulation running on Javascript, and I'm using HTML Canvas for the graphics. The problem is that there're hundreds of objects (creatures), each one doing loops to search for food and predators, and for each of them there are dozens of genes (variables) that suffer mutation when they reproduce. Well, the graphics are very simple (they're just colorful cells shaped like circles or ellipses), but the whole nest of loops is killing the performance.
I'm using the animate() function, which calls itself through the requestAnimationFrame(animate). Well, inside this animate() function, besides doing the whole drawing and redrawing for every element on the screen every frame, I also loop the array of creatures to call the hunting() and update() methods to each of them. And there are 2 arrays of creatures (herbivores and carnivores), which contain hundreds of objects, and one of food, which can contain thousands. This means I'm looping through three arrays every frame, not to mention the loops that happen inside the creatures methods (for example, to look for food, a herbivore loops through all the foods in the screen, calculates the distance from all of them, and only then seeks it).
Bottom line: loops inside loops inside loops every frame. So my question is: are there any tips to improve the performance? Is there any tool that analyses the code and points which parts of it use the most memory? And are there (there probably are) more efficient ways of doing the animation?
Thank you in advance!