C#。结构设计。为什么16字节被推荐大小? [英] C#. Struct design. Why 16 byte is recommended size?

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

问题描述

我读的书Cwalina(发展和.NET应用程序的设计建议)。

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

他说,良好的设计结构有可能成为大小小于16字节(对于性能的目的)。

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

我的问题是 - 到底为什么会这样?

My questions is - why exactly is this?

和(更重要的),我可以有同样的效率较大的结构,如果我跑我的.NET 3.5(即将.NET 4.0)上的i7 64位应用程序在Win7的X64 (这是限制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 i7 under Win7 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 in stack all the time, the application is heavily multi-threaded and runs on sub-millisecond intervals, the current size of the struct is 64 byte.

推荐答案

只有你知道你的结构都在你的程序中使用。但是,如果不出意外,你随时可以测试它自己。例如,如果它的经常传递到其他功能,以下可以照亮你:

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;
}

尝试这样的事情再与presentative结构/类的,看看有什么结果,你得到的。 (在我的机器,上面的测试,类似乎〜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)

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

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