Does using functions make a performance hit?

I read something that said use as little function calls as possible to increase performance.

I was just wondering if this is true at all? Does moving some commands to a function called by the Update make a performance hit over just leaving those commands directly in the Update loop?

Function calls have a slight overhead, but this usually doesn’t make any noticeable difference. In a loop that is called many times in quick succession, you will sometimes get some extra speed by avoiding functions. For example, processing every pixel in a texture each frame will involve code something like:-

function Update() {
    for (i = 0; i < pixels.Length; i++) {
        // Operation on pixel's colour.
    }
}

For a 256x256 texture, this loop would iterate 65536 times. Since the colour operation is likely to be fairly lightweight, you would be better to use it inline in this loop rather than put it into a function. However, in most other cases, the usefulness of functions is much more important than the very small overhead.

Doesn’t the JIT compiler automatically inline functions as appropriate? Or not?

–Eric

I’m curious about this as well. I believe there are some rules for functions to be inlined but I don’t recall what they are. Perhaps the function size. Knowing when a function gets inlined would be an important piece of information. It makes me miss good old C where you decide what is inlined.

In Soviet Unity, function inlines YOU!

…Sorry. :wink:

–Eric

If I remember, the C# compiler doesn’t do much inlining and the JIT only does it in a few specific cases. I’ve also found that with tight loops like that in Unity, function calls do detectably take extra time, so something like:-

for (i = 0; i < pix.Length; i++) {
    pixels[i].r = 0.1;
    pixels[i].g = 0.1;
    pixels[i].b = 0.1;
}

Is slower than using the Color constructor (and this doesn’t allocate memory, since it’s a struct - it’s effectively just a function call). As I said, it’s usually better not to worry about functions, but in a long, tight loop, you can sometimes squeeze a bit of extra speed out by inlining manually.

Good information here!

You do mean faster above, though, yes?

That is, using the struct assignment is slightly faster than using the Color constructor, since the latter has the overhead of a call?

Thanks.