How can use C# to make a loop run at maximum speed without stalling game time?

I’m a beginner using C#. This question is built on the first question I asked on unity answers. This is because though I had success in preventing my simulation from freezing on play, the previous solution was very slow. I am having trouble grasping how to integrate these standard functions that run every frame, with lengthy computational tasks which ideally disregard the advancement of frames until compete.

I should also point out that it is only when I do a pair of nested loops that this becomes intolerably slow using the way that I know how to do this.

Over-use of loops every frame can easily cause slowdown. Co-routines perform actions spread over multiple frames which allow for the same loops to occur but not all at once, which is fine in most situations. Check out:

“print” (or Debug.Log which is called inside print) Is very slow in the editor. It’s only ment for debugging purposes. However when you create a standalone build it runs much faster. The result can be viewed in the output_log.txt.

It’s not really clear what you actually want to do, so we can’t suggest solutions if we don’t know what you’re actually doing / you want to achieve.

In general if you do pure computing in your for loops which doesn’t involve the Unity API you can use a seperate threads for it, just keep in mind that you have to synchronise them when you’re done.

I’m fairly new to Unity so this might not be possible but look into threading. Most systems (even mobile devices) are multicore these days. Pushing the work onto a second core via a second thread will give you max CPU through put without hindering the primary/display thread. If your second thread runs too long, you’ll be stuck waiting for it however so be careful - threading can be deceptively tricky if you’re not experienced with it.

Seems I cannot post twice to the same question, so I’ll edit this old answer.

Are you allocating memory between each frame? Memory allocation can be rather expensive, especially if you’re fragmenting system memory and the GC is constantly reorganizing memory behind your back.