The first time a method is executed, it's 10x slower (at least). How?

Hi, there’s a method in my code where the first time you call it, it is much much slower, at least 10x, according to the profiler. Meaning calls like List.Remove (operating on a local variable) take much longer than on subsequent calls, even with the same number of elements. How is this possible? Or is it just the profiler not being truthful?

One of my customers posted screenshots of this phenomenon on this page: http://forum.unity3d.com/threads/168074-Master-Audio-RELEASED-Complete-audio-setup-amp-control-tool/page65

Any ideas? I fixed a few things but it hasn’t made a big dent on the first call performance. Extremely stumped.

I also found this similar thread that didn’t offer much insight: http://answers.unity3d.com/questions/674189/first-time-a-method-is-executed-is-4-times-slower.html

Thanks in advance for any ideas :slight_smile:

JIT compiling the method and all the uncompiled methods deeper in the call stack?

Loading resources (eg: the sound) into memory?

It’s not loading the sound into memory, this happens even with Audio Clips already filled out in the Audio Source component before hitting play.

JIT compiling…well the same MonoBehavior already called its Awake event before I called the slow-then-fast method, so I believe it’s already compiled the whole class at that point right?

Are you sure this is the case? Having a clip filled out in a prefab / scene object just sets an ID. The clip could be lazy loaded.

I don’t know the specifics, but even if the method was already compiled, other methods deeper in the call stack could still need to be compiled.

But I’m guessing it’s due to loading the sound. In my game there are sometimes stutters the first time a sound plays, though that could also be attributed to the corresponding graphics. Either way it implies some sort of resource loading.

Yes, I’m sure about the clip. Even if I comment out the whole part that actually plays the audio, the other methods before it (list add / remove) still take exponentially longer than they do on the next call.

It’s extremely weird. I may do some more testing when I have time.

Yeah on my game I get stutters only on sounds that are loaded via Resource files, because resource loading unfortunately blocks the thread (until Unity 5 gives us something better).

Well that makes it sound like it’s JIT then. What are the generic parameters of those collections?

Have you tried prewarming your plugin ? Try to either preallocate some memory or fake play a sound so unity hooks onto the sound driver before that first sound is played.

integer.

I tried prewarming briefly but dismissed doing it for real because I wanted to know why this was happening. I’ll try again for real this time.