11

I'm starting to learn Shaders now (HLSL, GLSL) and I saw a lot of tutorials where there weren't many variables created and that made reading harder. I was wondering if the creation of new variables affect the performance of the shader.

So, for example (in CG):

Is this

    inline float alphaForPos(float4 pos, float4 nearVertex){
            return (1.0/_FogMaxRadius)*clamp(_FogRadius - max(length(pos.z - nearVertex.z),length(pos.x - nearVertex.x)), 0.0, _FogRadius)/_FogRadius;
    }

Faster than this?

    inline float alphaForPos(float4 pos, float4 nearVertex){
        float distX = length(pos.x - nearVertex.x);
        float distZ = length(pos.z - nearVertex.z);
        float alpha = 0.0;
        alpha = _FogRadius - max(distZ,distX);
        alpha = clamp(alpha, 0.0, _FogRadius);
            return (1.0/_FogMaxRadius)*alpha/_FogRadius;
    }
Hodor
  • 166
  • 1
  • 8
  • 2
    Shader hardware does not have a call stack, so concepts like inlining and variable scope are quite different; however how you setup the variables in your function declaration ***is*** important. In GLSL, you can use storage qualifiers in function declarations (e.g. `alphaForPos (in vec4 pos, in vec4 nearVertex)`) to tell the compiler to make a local copy of the variable if you made changes to the value inside the function body. `inout`, on the other hand, means that any changes made inside the function are allowed to propagate outside of it and no copy is necessary. – Andon M. Coleman Dec 23 '13 at 00:41
  • So is kind like passing as reference in C# and it doesn't make a copy such as using the const Object &var in C++, right? – Hodor Dec 23 '13 at 05:53
  • Yes, you can think of it that way. Making copies of variables is not as unpredictably expensive as in a language like C++, where it may invoke a non-trivial copy constructor, but you still have to deal with limited register space, wasted clock cycles, etc. – Andon M. Coleman Dec 24 '13 at 01:41

1 Answers1

11

This won't affect performance.

Everything gets inlined at the end of the day and the optimising part of the compiler won't care about separate variables by the time optimisation has finished.

I compiled two simple pixel shaders that call these two functions and both compile down to 9 instructions in HLSL.

Go for readability and trust that the compiler will do the right thing (on this at least :)).

Adam Miles
  • 3,504
  • 17
  • 15
  • Makes a lot of sense to check the number of instructions in the compiled shader. In the compiler we trust :) – Hodor Dec 23 '13 at 05:54