Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I avoid creating multiple variables when programming a shader?

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;
    }
like image 825
Hodor Avatar asked Dec 22 '13 06:12

Hodor


1 Answers

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 :)).

like image 126
Adam Miles Avatar answered Sep 20 '22 01:09

Adam Miles