为什么 16 字节是 C# 中 struct 的推荐大小? [英] Why is 16 byte the recommended size for struct in C#?

查看:25
本文介绍了为什么 16 字节是 C# 中 struct 的推荐大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 Cwalina 的书(关于 .NET 应用程序开发和设计的建议).

I read the Cwalina book (recommendations on development and design of .NET applications).

他说一个好的设计结构的大小必须小于 16 字节(出于性能目的).

He says that a good designed struct has to be less than 16 bytes in size (for performance purposes).

这是为什么?

而且(更重要的是)如果我在 Core i7 在 Windows 7 x64 下(此限制是否基于 CPU/操作系统)?

And (more important) can I have larger struct with same efficiency if I run my .NET 3.5 (soon to be .NET 4.0) 64-bit application on Core i7 under Windows 7 x64 (is this limitation CPU / OS based)?

再次强调 - 我需要尽可能高效的结构.我尽量把它一直放在堆栈上.该应用程序是多线程的,以亚毫秒为间隔运行,结构的当前大小为 64 字节.

Just to stress again - I need as efficient struct as it is possible. I try to keep it on the stack all the time. The application is heavily multi-threaded and runs on sub-millisecond intervals, and the current size of the struct is 64 bytes.

推荐答案

只有你知道你的结构是如何在你的程序中使用的.但是,如果不出意外,您始终可以自己进行测试.例如,如果它经常被传递给其他函数,以下内容可能会启发您:

Only you know how your structs are being used in your program. But if nothing else, you can always test it for yourself. For instance, if it's frequently passed to other functions, the following may illuminate you:

class MainClass
{
    static void Main()
    {
        Struct64 s1 = new Struct64();
        Class64 c1 = new Class64();
        DoStuff(s1);
        DoStuff(c1);
        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (int i = 0; i < 10000; i++)
        {
            s1 = DoStuff(s1);
        }
        sw.Stop();
        Console.WriteLine("Struct {0}", sw.ElapsedTicks);
        sw.Reset();

        sw.Start();
        for (int i = 0; i < 10000; i++)
        {
            c1 = DoStuff(c1);
        }
        sw.Stop();
        Console.WriteLine("Class {0}", sw.ElapsedTicks);
        sw.Reset();

        Console.ReadLine();
    }
}

与:

public class Class64
{
    public long l1;
    public long l2;
    public long l3;
    public long l4;
    public long l5;
    public long l6;
    public long l7;
    public long l8;
}
public struct Struct64
{
    public long l1;
    public long l2;
    public long l3;
    public long l4;
    public long l5;
    public long l6;
    public long l7;
    public long l8;
}

用有代表性的结构/类尝试这种事情,看看你会得到什么结果.(在我的机器上,上面的测试,类似乎快了大约 3 倍)

Try this sort of thing with representative structs/classes, and see what results you get. (On my machine, above test, the class seems ~3 times faster)

这篇关于为什么 16 字节是 C# 中 struct 的推荐大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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