The Benefits of Constants

前端 未结 14 1877
南笙
南笙 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:25

    Certainly for a language like C and Ada, the compiler will put the value from the constant directly into the assembler instruction, meaning that no swapping of registers or reading from memory will be necessary over and above what is required to run the program. This means two things: the main one is speed (probably not so noticeably in many applications, unless they are embedded) and the second is memory usage (of both the program's final binary size and its runtime memory footprint).

    This behaviour will come down to the language and the compiler, as the language will dictate any assumptions made by you (the programmer) and therefore the constraints to the efficiency of the language; and the compiler because its behaviour could change from treating your constant like any other variable to pre-processing your code and optimising the binary speed and footprint as much as possible.

    Secondly, as was stated by itsmatt and jball, it enables you to logically consider the item as a constant configuration item rather than a 'variable'; especially in higher level programming languages and interpreted languages.

提交回复
热议问题