多次调用对象的方法与多次构造对象

发布于 2024-09-05 20:14:47 字数 416 浏览 3 评论 0原文

我有一个名为 myData 的列表,我想对列表中的每个元素应用特定的方法 (someFunction)。通过对象的构造函数调用方法是否比对一个特定对象实例化多次调用同一方法慢?

换句话说,这是:

for(int i = 0; i < myData.Count; i++)
    myClass someObject = new myClass(myData[i]);

比这个: 慢吗

myClass someObject = new myClass();
for(int i = 0; i < myData.Count; i++)
    someObject.someFunction(myData[i]);

如果是的话,慢多少?

I have a List called myData and I want to apply a particular method (someFunction) to every element in the List. Is calling a method through an object's constructor slower than calling the same method many times for one particular object instantiation?

In other words, is this:

for(int i = 0; i < myData.Count; i++)
    myClass someObject = new myClass(myData[i]);

slower than this:

myClass someObject = new myClass();
for(int i = 0; i < myData.Count; i++)
    someObject.someFunction(myData[i]);

?

If so, how much slower?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

能怎样 2024-09-12 20:14:47

前一种方法可能会导致流程工作集显着增加。它还可能会给 Windows 带来内存压力,导致其他应用程序被换出到磁盘。

此外,它会给 CLR 垃圾收集器带来很大的压力,因为您创建的每个新对象都会被跟踪以进行收集。

它会慢多少很大程度上取决于您创建的对象的大小和数量。

The former approach might result in significant increase of your process working set. It also might put a memory pressure on Windows, causing other apps to be swapped out to the disk.

Also, it will put a lot of pressure on the CLR garbage collector, since each new object you create will be tracked for collecting.

How much slower it will be depends a lot on the size and the number of objects you are creating.

白色秋天 2024-09-12 20:14:47

你可以让它更快,如果你使用静态方法,请使用 Visual Studio 2010 中的 Code Analisys,它会警告你,如果某些方法是静态的候选方法。

You could make it even faster, if you use an static method, please use Code Analisys from visual studio 2010, it will warn you, if some method is candidate for static.

蝶…霜飞 2024-09-12 20:14:47

从性能角度来看,第二个代码块很可能会更快,因为它没有对象实例化和垃圾收集的额外开销。

From a performance perspective, the second block of code will most likely be faster as it does not have the additional overhead of object instantiation and garbage collection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文