C指针,相较于直接结构成员访问 [英] C pointers vs direct member access for structs

查看:107
本文介绍了C指针,相较于直接结构成员访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有类似下面的结构...

Say I have a struct like the following ...

typedef struct {
  int WheelCount;
  double MaxSpeed;
} Vehicle;

...我有这种类型的全局变量(我很清楚全局的缺陷,这是一个嵌入式系统,这是我没有设计,以及他们是不幸的,但必要之恶。)是否有更快的直接或通过指针访问结构的成员?即

... and I have a global variable of this type (I'm well aware of the pitfalls of globals, this is for an embedded system, which I didn't design, and for which they're an unfortunate but necessary evil.) Is it faster to access the members of the struct directly or through a pointer ? ie

double LocalSpeed = MyGlobal.MaxSpeed;

double LocalSpeed = pMyGlobal->MaxSpeed;

我的一个任务是简化和修复最近继承嵌入式系统。

One of my tasks is to simplify and fix a recently inherited embedded system.

推荐答案

在一般情况下,我会说去的第一个选项:

In general, I'd say go with the first option:

double LocalSpeed = MyGlobal.MaxSpeed;

这少了一个反引用(你没有找到指针,则取消引用它来得到它的位置)。它也简单,更易于阅读和维护,因为你不需要除了结构创建指针变量。

This has one less dereference (you're not finding the pointer, then dereferencing it to get to it's location). It's also simpler and easier to read and maintain, since you don't need to create the pointer variable in addition to the struct.

话虽这么说,我不认为你会看到任何性能差异将是noticable,即使是在嵌入式系统中。双方将是非常,非常快的访问时间。

That being said, I don't think any performance difference you'd see would be noticable, even on an embedded system. Both will be very, very fast access times.

这篇关于C指针,相较于直接结构成员访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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