将类中的方法替换为扩展方法更有效吗?

Ton*_*Nam 4 c# performance extension-methods

我递归地使用这个 apreach快速查找目录中的所有文件.

无论如何,我将信息存储在结构中的每个文件中:

struct Info 
{
    public bool IsDirectory;
    public string Path;
    public FILETIME ModifiedDate;
}
Run Code Online (Sandbox Code Playgroud)

所以现在我正在尝试决定天气将辅助方法放在该结构或其他地方以提高效率.

辅助方法是:

struct Info 
{
    public bool IsDirectory;
    public string Path;
    public FILETIME ModifiedDate;

    // Helper methods:
    public string GetFileName(){ /* implementation */ }
    public string GetFileSize(){ /* implementation */ }
    public string GetFileAtributes() { /* implementation */ }
    // etc many more helper methods
}
Run Code Online (Sandbox Code Playgroud)

我在内存中保存了数千个文件,我不知道在Info中使用这些方法是否会影响性能.换句话说,最好删除这些方法并使它们成为扩展方法:

public static class ExtensionHelperMethods
{
    static public string GetFileName(this Info info){ /* implementation */ }
    static public string GetFileSize(this Info info){ /* implementation */ }
    static public string GetFileAtributes(this Info info) { /* implementation */ }
    // etc many more helper methods
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是因为Info是一个实例结构,然后内部的那些方法导致更多的内存?如果Info是实例结构,那么每个方法在内存中都有不同的地址?

我尝试了两种技术,但我似乎没有看到差异.也许我需要尝试更多的文件.


编辑

这是为了证明@Fabio Gouw是正确的:

// This program compares the size of object a and b
class Program
{
    static void Main(string[] args)
    {
        InfoA a = new InfoA();
        InfoB b = new InfoB();

        if (ToBytes(a).Length == ToBytes(b).Length)
        {
            Console.Write("Objects are the same size!!!");
        }

        Console.Read();
    }

    public static byte[] ToBytes(object objectToSerialize)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream memStr = new MemoryStream();

        try
        {
            bf.Serialize(memStr, objectToSerialize);
            memStr.Position = 0;

            var ret = memStr.ToArray();

            return ret;
        }
        finally
        {
            memStr.Close();
        }
    }

    [Serializable]
    struct InfoA
    {
        public bool IsDirectory;
        public string Path;
    }

    [Serializable]
    struct InfoB
    {
        public bool IsDirectory;
        public string Path;

        public string GetFileName()
        {
            return System.IO.Path.GetFileName(Path);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fab*_*bio 5

方法不会干扰对象大小,只有字段可以做(方法是行为;字段是数据,而这些是存储在内存中).将它们放入Info类或作为扩展方法的决定只是一个设计问题.

此问题与您的问题类似:将方法转换为静态方法时的内存使用情况