The Benefits of Constants

前端 未结 14 1902
南笙
南笙 2021-02-04 07:46

I understand one of the big deals about constants is that you don\'t have to go through and update code where that constant is used all over the place. Thats great, but let\'s s

14条回答
  •  渐次进展
    2021-02-04 08:21

    A lot of this depends on how good your optimizer is.

    A good optimizer will replace const references with literal values during compilation. This saves processor cycles since the generated machine code is working with immediate values instead of having to load a value from memory.

    Some optimizers will recognize that a value is not modified after it is declared, and convert it to a constant for you. Do not rely on this behavior.

    Also, whenever possible, your code should enforce the assumptions you've made during development. If a "variable" should never be changed, declaring it as a constant will help ensure that neither yourself nor any other developers that come along later will unwittingly modify a "constant".

提交回复
热议问题