Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question Usage of const in hlsl

Discussion in 'General Graphics' started by fleity, Mar 30, 2023.

  1. fleity

    fleity

    Joined:
    Oct 13, 2015
    Posts:
    256
    Hi everyone,

    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)?
     
  2. c0d3_m0nk3y

    c0d3_m0nk3y

    Joined:
    Oct 21, 2021
    Posts:
    384
    You can do this in C++ code too.

    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).
     
    fleity likes this.
  3. burningmime

    burningmime

    Joined:
    Jan 25, 2014
    Posts:
    827
    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.
     
    fleity likes this.
  4. fleity

    fleity

    Joined:
    Oct 13, 2015
    Posts:
    256
    thanks to both of you very much
    your answers have been more concise than any information I found in half an hour of searching via google
     
    c0d3_m0nk3y likes this.