C#静态VS实例方法 [英] C# static vs instance methods

查看:113
本文介绍了C#静态VS实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是冒险,这可能是一个问题福利局但在这里不用。我很想一个方法添加到一个类可能有可能成千上万的内存实例在给定时间。现在,另一种选择是创建一个静态方法的静态类,只是创建[静态]法那里,而不是在类的实例方法。像这样:

I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

这:

public static class PetOwner
{
    public static void RenamePet(Pet pet, string newName)
    {
        pet.Name = newName;
    }
}



而不是这样的:

Instead of this:

public class Pet
{
    public string Name { get; set; }

    public void Rename(string newName)
    {
        this.Name = newName;
    }
}



我只是想知道,如果静态类替代办法需要相当少的内存。

I'm just wondering if the static class alternative would take considerably less memory.

谢谢!

推荐答案

只有数据字段要求每个实例存储,在一定条件下和最佳化。例如,一类10000实例定义一个Int32成员将消耗〜40000字节的内存。

Only data fields require storage per instance, subject to certain conditions and optimisations. For instance, 10,000 instances of a class that define an Int32 member will consume ~40,000 bytes of memory.

字符串,而另一方面,不是由于实习这么简单。你可以试试这个作为一个例子:

Strings, on the other hand, are not so simple due to interning. You can try this as an example:

object.ReferenceEquals("", string.Empty) // returns true!

如果同一万实例也定义一个字符串,该字符串是每个实例相同,则你将有10,000个引用相同的数据指出,减少开销很大(但在32位环境中,有被引用占用的4万人字节)。

If the same 10,000 instances also define a string, and that string is the same for each instance, then you're going to have 10,000 references pointing at the same data, reducing overhead considerably (but in a 32-bit environment, there's another 40,000 bytes taken up by the references).

方法,因为被别人指出的那样,无论是静态或实例,只加载一次。

Methods, as pointed out by others, whether static or instance, are only loaded once.

使用实例或静态方法的决定不是由性能原因影响的,但由该方法打算如何使用。在你的情况,该方法需要的类型作为其第一个参数的一个实例,因此它可能也有一个实例方法。

The decision to use either instance or static methods is not influenced by performance reasons, but by how the method is intended to be used. In your case, the method requires an instance of the type as its first parameter so it may as well be an instance method.

静态方法,根据我的经验,最有用作为替代一种类型的构造用于返回一个新实例。构造,调用一次,必须要么返回一个新的实例或抛出异常,这可能不是所期望的。静态方法可以返回null如果事情失败,或者返回一个缓存实例(后者是有用的,如果构造是一个昂贵的操作)。

Static methods, in my experience, are most useful as an alternative to a type's constructor for returning a new instance. Constructors, once invoked, have to either return a new instance or throw an exception, which may not be desirable. Static methods can return null if something fails, or return a cached instance (the latter of which is useful if the constructor is an expensive operation).

这篇关于C#静态VS实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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