C变量声明的效率 [英] Efficiency of C Variable Declaration

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

问题描述

在C中声明一个变量(例如int xunsigned long long var)需要花费多长时间?我想知道这样做是否会使我的代码更快.

How long does it take to declare a variable in C, for example int x or unsigned long long var? I am wondering if it would make my code any faster in something like this.

for (conditions) {
    int var = 0;
    // code
}

这样做会更快吗,还是更容易做到呢?

Would it be faster to do this, or is it easier not to?

int var;
for (conditions) {
    var = 0;
    // code
}

感谢您的帮助.

推荐答案

每当您对性能有疑问时,最好的办法是在其周围环绕一个循环(数百万次迭代)并对其计时.但是,在这种情况下,您可能会发现没什么区别.

Whenever you have a question about performance, the best thing to do is wrap a loop around it (millions of iterations) and time it. But, in this case, you will likely find that it makes no difference.

正确表达代码的意图更为重要.如果您需要循环外的变量,请在循环外进行修饰.如果仅需要在循环内使用变量,请在循环内声明它.

It is more important to properly express the intentions of your code. If you need the variable outside your loop, delare it outside. If you only need the variable inside the loop, declare it inside.

您应该始终在尽可能小的范围内声明和初始化变量.

无论如何,您都不必担心这些微优化类型(在罕见的情况下,最罕见的情况除外).如果您真的需要担心潜在的纳秒级性能改进,请衡量差异.变量声明不太可能成为应用程序中最大的瓶颈.

You shouldn't be worrying about those types of micro-optimizations anyway (except in the rarest, rarest of cases). If you really need to worry about potential nano-second performance improvements, measure the difference. It is very unlikely that your variable declarations will be the largest bottleneck in your application.

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

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