C pointers vs direct member access for structs

前端 未结 9 2656
抹茶落季
抹茶落季 2020-12-16 17:59

Say I have a struct like the following ...

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

... and I have a global variabl

相关标签:
9条回答
  • 2020-12-16 18:04

    I suppose that, if this makes a difference at all, that would be architecture-dependent.

    0 讨论(0)
  • 2020-12-16 18:06

    In general, accessing the struct directly would be quicker, as it won't require an extra pointer dereference. The pointer dereference means that it has to take the pointer (the thing in the variable), load whatever it points to, then operate on it.

    0 讨论(0)
  • 2020-12-16 18:06

    Direct member access is faster (for pointers you'd get one pointer dereference operation more, typically). Although I'm having a hard time imagining it in a situation where it'd be a problem, performance or otherwise.

    0 讨论(0)
  • 2020-12-16 18:12
    struct dataStruct
    {
        double first;
        double second;
    } data;
    
    int main()
    {
        dataStruct* pData = &data;
    
        data.first = 9.0;
        pData->second = 10.0;
    }
    

    This is the assembly output using VS2008 release mode:

        data.first = 9.0;
    008D1000  fld         qword ptr [__real@4022000000000000 (8D20F0h)] 
    
        pData->second = 10.0;
    008D1006  xor         eax,eax 
    008D1008  fstp        qword ptr [data (8D3378h)] 
    008D100E  fld         qword ptr [__real@4024000000000000 (8D20E8h)] 
    008D1014  fstp        qword ptr [data+8 (8D3380h)] 
    
    0 讨论(0)
  • 2020-12-16 18:17

    In C, there should be no difference, or a insignificant performance hit.

    C students are taught:

    pMyGlobal->MaxSpeed == (*pMyGlobal).MaxSpeed
    

    You should be able to compare the disassembly of them both to convince yourself that they are essentially the same, even if you aren't an Assembly-code programmer.

    If you are looking for a performance optimization, I would look elsewhere. You won't be able to save enough CPU cycles with this kind of micro-optimization.

    For stylistic reasons, I prefer the Structure-Dot notation, especially when dealing with singleton-globals. I find it much cleaner to read.

    0 讨论(0)
  • 2020-12-16 18:19

    On your embedded platform, it's likely that the architecture is optimized in such a way that it's essentially a wash, and even if it wasn't you would only ever notice a performance impact if this was executed in a very tight loop.

    There are probably much more obvious performance areas of your system.

    0 讨论(0)
提交回复
热议问题