单独传递一个结构或其成员会更快吗? [英] Is it faster to pass a struct or its members individually?

查看:72
本文介绍了单独传递一个结构或其成员会更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

struct Foo
{
    int A;
    int B;
};

哪个方法调用更快?

void Bar(Foo MyFoo)

void Bar(int A, int B)

?

还是一样?

推荐答案

这实际上可以取决于平台和编译器.尤其是当sizeof(Foo)很小时.

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

如果int是16位,则只需要32位的一次堆栈压入,这比64位体系结构上的指针要少,但在这些int上通常超过16位.

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.

侧面说明:如果您进入C ++领域,事情可能会变得有些复杂,但是您应该将struct作为const引用传递,它基本上是一个指针,但是给计算机带来了更多的变聪明的机会. .

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.

这篇关于单独传递一个结构或其成员会更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆