使用静态方法与实例化包含方法的类的性能 [英] Performance of using static methods vs instantiating the class containing the methods

查看:47
本文介绍了使用静态方法与实例化包含方法的类的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#开发一个项目.以前的程序员并不了解面向对象的程序设计,因此大多数代码都存储在数十个方法中,有时甚至数百个方法中,只有一个类.重构这样的项目是一项艰巨的任务,因此我现在已经半学会与之共存.

I'm working on a project in C#. The previous programmer didn't know object oriented programming, so most of the code is in huge files (we're talking around 4-5000 lines) spread over tens and sometimes hundreds of methods, but only one class. Refactoring such a project is a huge undertaking, and so I've semi-learned to live with it for now.

只要在其中一个代码文件中使用方法,实例化该类,然后在对象实例上调用该方法.

Whenever a method is used in one of the code files, the class is instantiated and then the method is called on the object instance.

我想知道这样做是否会对性能产生明显的影响?我是否应该暂时"将所有方法设为静态,最重要的是,应用程序将以任何方式从中受益吗?

I'm wondering whether there are any noticeable performance penalties in doing it this way? Should I make all the methods static "for now" and, most importantly, will the application benefit from it in any way?

推荐答案

来自此处,每次调用实例方法时,静态调用的速度都比构造实例快4至5倍.但是,我们仍然只在谈论每个调用数十纳秒,因此除非您真的有紧密的循环调用方法数百万次,并且通过在外部构造单个实例而获得相同的好处,否则您不太可能注意到任何好处.循环并重用它.

From here, a static call is 4 to 5 times faster than constructing an instance every time you call an instance method. However, we're still only talking about tens of nanoseconds per call, so you're unlikely to notice any benefit unless you have really tight loops calling a method millions of times, and you could get the same benefit by constructing a single instance outside that loop and reusing it.

由于必须更改每个呼叫站点才能使用新的静态方法,因此最好将时间花在逐步重构上.

Since you'd have to change every call site to use the newly static method, you're probably better spending your time on gradually refactoring.

这篇关于使用静态方法与实例化包含方法的类的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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