c - 如何编写更高效的代码

标签 c performance premature-optimization

世纪之问?我基本上想知道,如果我将此代码编写为几个不同的变量或使用小型数组,哪个会更有效。

int x = 34;
int y = 28;
int z = 293;

对比

double coordinate[3] = {34, 28, 293};

我有一个坐标结构,我将按以下方式使用它:

typedef struct coordinates_t {
    double x = 0.0;
    double y = 0.0;
    double z = 0.0;

} coordinates;


typedef struct car_t {
    coordinates start; // car starting point
    coordinates location; // car current Location
    coordinates targCarVector; // Vector to car from target
    coordinates altitude; // Altitude of car
    coordinates distance; // Distance from car start to current position
} car;

我需要做如下事情:

distance = car1.location - car1.start;

如果我不使用数组,我将不得不编写很多行代码,但如果我使用数组,我将不得不使用循环。数组和循环是否占用更多内存/CPU 资源?我基本上是想看看哪种是编写此代码的最有效方法。

谢谢, 半羊

最佳答案

效率比可维护性和可读性更重要吗?答案是不。即使您有一个时间紧迫的应用程序,您也会将 90% 的时间花在不到 10% 的代码上,因此只有这 10% 的代码需要尽可能高效地编码。

如果您没有测量并找出哪 10% 是罪魁祸首,您几乎肯定会优化一开始就不会占用太多运行时间的代码。这是浪费时间。

关于c - 如何编写更高效的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3586633/

相关文章:

jquery - 在切换 DOM 元素的可见性之前是否值得检查其可见性?或者这是不成熟的优化?

c++ - 为什么 C/C++ 字符串文字声明必须是单行的?

c# - 设置像素数据的最佳方法?

sql-server - 对连接到网络存储设备的数据库进行负载测试

php - 使用 PHP/Apache 缓存操作码的最简单方法是什么?

c++ - 重新安排条件评估会加速循环吗?

c++ - 为什么 swap 在 C++ 中不使用 Xor 操作

c - 段错误 - 套接字编程

c - 为什么在使用 getchar() 的 while 循环中移动 printf() 会产生不同的结果?

c - 如何从 gdb 读取 fread 值