views:

125

answers:

1

We were trying to sort a collection of FileInfo objects in .NET. We implemented our IComparer to ensure that FileInfo objects were sorted based on our criteria. We then noticed that performance of sorting the FileInfo objects was many times slower than just ints. On a hunch (and remembering how references work in C) we were able to improve performance by using local variables to limit the number of times we referenced FileInfo properties.

My idea was that local variables would be faster to access than properties on objects. I think that this makes sense in the world of unmanaged code, where I can actually picture how the stack works and how values are referenced. However, I know the world of managed code can be more complicated under the covers. My question is: Can these basic ideas of memory management and program flow in un-managed code be generally projected into the world of managed code?

Eventually with the help from KeeperOfTheSoul, we were able to track this down to how we were mocking the FileInfo object. For that reason, I have added a RhinoMock tag to this quesiton.

A: 

There shouldn't really be a speed difference between sorting a value type compared to a reference type except for the implementation of the comparison method. If I implemented a comparison method that used sin then the ints would sort slowly as well.

Accessing a property does involve a method call, whilst accessing a local variable, either the value is directly on the stack or already in a register. However, simple properties can be optimized by the JIT to provide something similar to inlining.

In this case I think the problem is that FileInfo can require a file system read to get the properties value, and if FileInfo doesn't internally cache the value it could end up performing this read repeatedly.

KeeperOfTheSoul
I don't think the FileInfo object is directly accessing the file system. In our test we were actually mocking FileInfo objects using RhinoMock. This brings up a good point, could it have just been the RhinoMock framework that was slowing our tests down?
L. Moser
Probably, I think rhino mock places it through some reflection, certainly enough to stop JIT optimisations from being as efficient.
KeeperOfTheSoul
I just ran some tests to verify and it certainly looks like performance on the mocked objects. Thanks for the help.
L. Moser