Daniela
Daniela

Reputation: 61

GLSL performance differences between function call vs. inlining

Does it make a performance difference in GLSL if something simple like a + operator is wrapped into a function?

So for example these two scenarios:

Example 1:

in uniform float uValueA;
in uniform float uValueB;

void main()
{
    float value = uValueA + uValueB;
    // [...]
}

Example 2:

in uniform float uValueA;
in uniform float uValueB;

float addValues(float a, float b)
{
    return a + b;
}

void main()
{
    float value = addValues(uValueA, uValueB);
    // [...]
}

is there any difference in the compiled end product? Or do they result in the same number of instructions and performance?

Upvotes: 6

Views: 5314

Answers (2)

bernie
bernie

Reputation: 10390

When I tested this specific case a couple years ago, I found no performance difference between functions or in-line code. If I remember correctly, at the time I used tools from Nvidia and/or AMD to look at the assembly code generated from the GLSL files. This also confirmed that the assembly was identical whether I used functions or not. This suggests that functions are inlined.

I suggest you have a look for yourself at the assembly code of both versions of your shader to convince yourself. This question (https://gamedev.stackexchange.com/questions/65695/aquire-disassembly-of-shader-code) explains some ways to get this information.

Upvotes: 4

MuertoExcobito
MuertoExcobito

Reputation: 10039

You essentially can assume nothing about the optimization of your shader, because the compilation is vendor specific. It would make sense that a compiler would optimize this very simple case, and inline the function, making the two equivalent, but that is in no way guaranteed. They could in theory insert a million no-ops for every function call (although, the person who wrote their compiler might be fired :)).

That said, you can "pre-optimize" your GLSL code, such that these sorts of optimizations are performed before the code is sent to the compiler (generally done offline). The glsl-optimizer is frequently used for this purpose, and used built into the Unity engine.

Upvotes: 0

Related Questions