# if and #ifdef in shader code for performance

## Recommended Posts

if and #ifdef which is better used in shader code and does not affect the performance seriously?
#ifdef _DEBUG_
return float4(1.0f,0,0,1);
#else
clip(-1);
#endif


if (bDeug)
return float4(1.0f,0,0,1);
else
clip(-1);



##### Share on other sites
Obiously the first one.
Preprocessor directives are resolved in compiling time, so there are no performance slowing in execution.

##### Share on other sites
There is a huge difference.

#ifdef is a preprocessor keyword (as it starts with #). It is executed BEFORE the shader is COMPILED and can be used to exclude some parts of the source code.

if() is branch statement. It is executed at runtime of the shader and can have quite severe performance penalities.

Always use #ifdef if already you know what you want to be executed at the time the shader is compiled.

Best regards,
Porthos

##### Share on other sites
well the whole point of #ifdef's are to either have the code contained within it compiled and run/accessable or not compiled with the rest of the program at all. If you don't want to be able to toggle the code contained on an off then use #ifdef and just define debug or whatever when you want to compile a test version, and then undefine it and recompile for a normal version... but if you want to be able to toggle the section running while the program is currently running then of course you have to use a normal variable.

in terms of performance - one little if statement isn't going to make a bit of difference if the test fails and the code doesnt run.

maybe a better solution is

#ifdef _DEBUG_  if (Debug) return float blah blah  else clip(-1);#else  clip(-1);#endif

this way you can compile your program with the option of toggling a debug var on and off, or you can compile the whole idea right out and just have it clip(-1).

##### Share on other sites
'if' has several meanings. It may be calculated at compile time if it refers to a uniform parameter. The uniform parameter's value is supplied when the shader is compiled ("compile ps_2_0 shader(parameter);").

For a program-wide debug flag, preprocessor may be good. If you want to select debug for specific shaders, at runtime, you can have different techniques for them, and compile with different uniform debug parameters.

(For normal code, 'if' can still be either defined as 'branch' or 'flatten', which will produce different code.)

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628367
• Total Posts
2982284

• 10
• 9
• 13
• 24
• 11