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.
Pointers are helpful because you can "move them around" more easily. Instead of having to copy over the whole stucture each time, you can just leave it where it is in memory and instead pass a pointer to it around.
Like every other data type, structure variables are stored in memory, and we can use pointers to store their addresses. Structure pointer points to the address of the structure variable in the memory block to which it points. This pointer can be used to access and change the value of structure members.
To access members of a structure using pointers, we use the -> operator. In this example, the address of person1 is stored in the personPtr pointer using personPtr = &person1; . Now, you can access the members of person1 using the personPtr pointer.
Similarly, we can have a Pointer to Structures, In which the pointer variable point to the address of the user-defined data types i.e. Structures. Structure in C is a user-defined data type which is used to store heterogeneous data in a contiguous manner.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With