C++: Structs slower to access than basic variables?

后端 未结 9 2423
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 03:45

I found some code that had \"optimization\" like this:

void somefunc(SomeStruct param){
    float x = param.x; // param.x and x are both floats. supposedly this          


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-13 04:21

    In an unoptimised code:

    • function parameters (which are not passed by reference) are on the stack
    • local variables are also on the stack

    Unoptimised access to local variables and function parameters in an assembly language look more-or-less like this:

    mov %eax, %ebp+ compile-time-constant
    

    where %ebp is a frame pointer (sort of 'this' pointer for a function).

    It makes no difference if you access a parameter or a local variable.

    The fact that you are accessing an element from a struct makes absolutely no difference from the assembly/machine point of view. Structs are constructs made in C to make programmer's life easier.

    So, ulitmately, my answer is: No, there is absolutely no benefit in doing that.

提交回复
热议问题