Is it faster to pass a struct or its members individually?

夙愿已清 提交于 2020-01-06 02:12:11

问题


If I have a

struct Foo
{
    int A;
    int B;
};

Which method call is faster?

void Bar(Foo MyFoo)

or

void Bar(int A, int B)

?

Or are they the same?


回答1:


This can actually be platform and compiler dependent. Especially when the sizeof(Foo) is small.

If the ints are 16 bit, only one stack push of 32 bits is needed, which is less than a pointer on 64 bits architectures, but on those ints are often more than 16 bits.

As separate arguments, each will be a separate push to the stack, unless the compiler does something clever,... Which it frequently does. This struct could likely be handled as a single push to the stack on most modern platforms.

When you get into more interesting structs that are still small, such as containing single chars or bit fields, passing the struct can be faster, even when passed by value.

But these are insignificant differences unless you're working on a platform closer to an old calculator than a cheap modern phone.

Chiming in with the rest; pass by reference is generally the fastest, but measurement or inspecting the generated assembly is the only way to be sure for the platform at hand.

Side note: If you cross into C++ land, things can get a bit more complicated, but there you should rather pass the struct as a const reference, which is basically a pointer, but gives the computer even more chances to be clever.




回答2:


In this case, they are the same.

The more parameters you pass in a fuction, the more expensive the call will be. This is due to multiple pushes on the stack on each call. Passing complete structures will be the same as passing each individual part of a struct. You should use pointers and references in such cases.

As paul stated, use void Bar(Foo* MyFoo)




回答3:


Spend a memory address (by reference) is better than spending the values (by values).



来源:https://stackoverflow.com/questions/29522741/is-it-faster-to-pass-a-struct-or-its-members-individually

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!