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