Amichai
Amichai

Reputation: 1154

Calling a method on an object a bunch of times versus constructing an object a bunch of times

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?

Upvotes: 0

Views: 103

Answers (3)

Fraga
Fraga

Reputation: 1451

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.

Upvotes: 1

Franci Penov
Franci Penov

Reputation: 76001

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.

Upvotes: 1

btreat
btreat

Reputation: 1554

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.

Upvotes: 0

Related Questions