0

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?

µBio
  • 10,668
  • 6
  • 38
  • 56
Amichai
  • 1,144
  • 1
  • 12
  • 21
  • 2
    Performance considerations aside, I think it's a bad idea to have an object constructor with side effects, particularly if the constructed object is never used, once constructed. – Dan Bryant Jun 14 '10 at 23:33
  • This is called premature optimization. OTOH, the second most likely. –  Jun 14 '10 at 23:34

3 Answers3

1

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.

Franci Penov
  • 74,861
  • 18
  • 132
  • 169
  • Why will the former put memory pressure on Windows? Won't each new object be deleted after every increment in the for loop? – Amichai Jun 14 '10 at 23:28
  • It won't be removed immediately when it goes out of scope. It has to wait for the garbage collection to come around. – Davy8 Jun 14 '10 at 23:30
  • As @Davy8 said, the GC is not going to collect every object immediately after it goes out of scope. Thus, the heap consumption of your app might grow considerably before the gen 0 collection kicks in. – Franci Penov Jun 15 '10 at 02:16
1

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.

Fraga
  • 1,361
  • 2
  • 15
  • 47
0

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.

btreat
  • 1,554
  • 8
  • 10