Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

embedded - C pointers vs direct member access for structs

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;

or

double LocalSpeed = pMyGlobal->MaxSpeed;

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...