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

查看:359
本文介绍了为什么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).

这到底是为什么?

并且(更重要的是)如果我在 64位应用程序,我可以具有相同的效率的更大结构吗? wikipedia.org/wiki/Intel_Core#Core_i7"rel =" noreferrer> Windows 7 x64下的Core i7 (此限制是否基于CPU/OS)?

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)?

再次强调-我需要尽可能有效的结构.我尝试将其始终保持在堆栈中.该应用程序具有大量的多线程功能,并且运行时间不到1毫秒,并且该结构的当前大小为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天全站免登陆