常量的好处 [英] The Benefits of Constants

查看:103
本文介绍了常量的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解有关常量的一件大事,就是您不必遍历并更新在各处使用该常量的代码。太好了,但是假设您没有明确将其声明为常量。有什么好处可以接受实际上不会发生变化的变量并使其恒定,这将节省处理时间和/或代码的大小...等吗?

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 say you don't explicitly declare it as a constant. What benefit(s) exist(s) to take a variable that HAPPENS to actually not be changed and make it a constant, will this save on processing, and/or size of code...etc?

基本上,我有一个程序,编译器在说一个特定的变量未更改,因此可以声明为常量,我只是想知道将常量限定符添加到该变量有什么好处? ,如果没什么区别,那么进行更改不会增加任何价值,因此也不会浪费时间(将相同的场景发生在一个以上的位置)并修复所有这些变量。

Basically I have a program that the compiler is saying that a particular variable is not changed and thus can be declared a constant, I just wanted to know what the benefit to adding the constant qualifier to it would be, if it makes no difference then making that change adds no value and thus no point wasting time (this same scenario occurs in more then one place) going back and "fixing" all these variables.

推荐答案

如果您将变量声明为常量,则优化程序通常可以通过常量折叠将其消除,从而既可以提高程序速度,又可以节省空间。例如,考虑以下情况:

If you declare a variable to be a constant, then the optimizer can often eliminate it via 'constant folding' and thus both speed up your program and save you space. As an example, consider this:

var int a = 5;
const int b = 7;
...
c = process(a*b);

编译器最终将创建一条指令,将a乘以7,并将其传递给 process ,将结果存储在c中。但是在这种情况下:

The compiler will end up creating an instruction to multiply a by 7, and pass that to 'process', storing the results in c. However in this case:

const int a = 5;
const int b = 7;
...
c = process(a*b);

编译器将简单地传递35进行处理,甚至不编写乘法。另外,如果编译器知道该进程没有副作用(即,是一个简单的计算),那么它甚至不会调用进程。它将c设置为process(35)的返回值,从而节省了函数调用。

The compiler will simply pass 35 to process, and not even code the multiply. In addition, if the compiler knows that process has no side effects (ie, is a simple calculation) then it won't even call process. It will just set c to be the return value of process(35), saving you a function call.

这篇关于常量的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆