I am asking out of sheer curiosity.
Recently I started using rider for all of my coding needs including shaders. I noticed the inspection encourages me to declare any variable that is not changing as a const (including function parameters).
I get that it makes sense to do this differentation but I have very rarely seen this in other peoples shader code (and not Unitys either) so I wonder if the code inspection can detect that this variable doesn’t change does the compiler too and take care of this completely?
Or is this really a meaningful optimization (even if it is very little)?
Writing const-correct code is an important tool for writing clean, bug-free code. I don’t think it has anything to do with optimization. It prevents you from writing methods with side effects in a const context (e.g. writing a getter method that also changes some state of the object).
The most useful use-cases for const are const methods, pointers to const data, references to const data (none of these exist in HLSL) and const literals.
const variables and const parameters have very little benefit as far as I know. I’ve seen them used in HLSL code but it comes down to personal preference if you want to use them. In my opinion, they just make the code much longer.
But again, const correctness as a whole is very important but you can’t really use most of it in HLSL since HLSL is not an object oriented language nor does it have pointers or references (everything is passed by value and all functions are inlined).
The shader compiler won’t care at all; it will fully analyze the program. There’s no optimization to be had.
The most likely explanation as for why Rider suggests it is because Rider’s HLSL analysis is based on the C++ analysis used in CLion. So it just suggests const everywhere because it suggests const everywhere in C++. You can turn it off if you find it annoying, it’s somewhere under code inspection settings.
I have been using const in my shaders, though I plan to remove them as I recently saw in the Unity docs that they recommend against using it (except for truly invariant constants)… that this should avoid confusing errors on some platforms.