使无状态方法静态化是好事还是坏事?
Is it good or bad practice to make stateless methods static?
如果 class 方法不依赖于 class' 状态,那么它可以是静态的。在这种情况下,将此类方法设为静态是好事还是坏事?
(标记为 C#,但可能适用于许多 OO 语言,其中方法必须是 class 成员。)
Visual Studio Code Analysis 和 ReSharper 建议将这些方法设为静态,因为它具有微小的性能优势:
Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
对于非 "performance-sensitive" 代码,这是个人喜好问题。如果我没有充分的理由不这样做,我个人会遵守 ReSharper 的建议。
Is it good or bad practice to make such methods static where this is
the case?
老实说,没有办法说 100% 这是好事还是坏事。许多人遵循一般规则,即如果可以将其设为静态,那么就这样做。它表明对状态没有要求,并且从技术上讲(至少在 C# 中)它要快一点。
也就是说,这完全取决于围绕方法的代码的组成,以及应用程序将如何发展。
如果 class 方法不依赖于 class' 状态,那么它可以是静态的。在这种情况下,将此类方法设为静态是好事还是坏事?
(标记为 C#,但可能适用于许多 OO 语言,其中方法必须是 class 成员。)
Visual Studio Code Analysis 和 ReSharper 建议将这些方法设为静态,因为它具有微小的性能优势:
Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
对于非 "performance-sensitive" 代码,这是个人喜好问题。如果我没有充分的理由不这样做,我个人会遵守 ReSharper 的建议。
Is it good or bad practice to make such methods static where this is the case?
老实说,没有办法说 100% 这是好事还是坏事。许多人遵循一般规则,即如果可以将其设为静态,那么就这样做。它表明对状态没有要求,并且从技术上讲(至少在 C# 中)它要快一点。
也就是说,这完全取决于围绕方法的代码的组成,以及应用程序将如何发展。