tags:

views:

93

answers:

1

Have a question about how to better optimize or speed things up. Currently my code seems to be running a bit slow...

I have the following classes

public class DataFoo : IFoo { }

public class Foo
{
     internal IFoo UnderlyingDataObject{get;set;}

     public Foo(IFoo f)
     {
          UnderlyingDataObject = f;
     }
}

Now, in many cases I end up needing or calling a method that will provide back a List. This method will initially get a array of DataFoo objects and will iterate over all returned objects instantiating a new Foo object passing in the DataFoo... Here's an example...

public List<Foo> GetListOfFoo(Guid id)
{
     DataFoo[] q = GetArrayOfDataFoo(id);
     List<Foo> rv = new List<Foo>();

     for(var i = 0; i < q.Length; i++)
     {
           rv.Add(new Foo(q[i]));
     }
     return rv;
}

The issue is that having to iterate over and instantiate like this seems pretty slow. I was curious if anyone might have suggestions on how to speed this up...

+3  A: 

Firstly, you should profile this carefully. Whenever you're looking at performance, don't try and guess what's going on -- measure everything. You will, more often than not, be surprised by the truth.

Your definition of GetListOfFoo could be improved slightly to avoid needless resizing of the List<Foo> by specifying the initial capacity:

 DataFoo[] q = GetArrayOfDataFoo(id);
 List<Foo> rv = new List<Foo>(q.Length);

But unless you're dealing with very large arrays and are concerning yourself with very small periods of time, then this won't make much difference.

There's nothing about the decorator pattern you're using that should effect your performance noticably unless you're talking about millions of updates a second or microsecond latencies.

I would like to see what GetArrayOfDataFoo is doing. My guess is that your issue is occurring outside what you have shown us.

Drew Noakes
Cheers; I missed the conversion ;-p
Marc Gravell
GetArrayOfDataFoo is using fluent nhibernate/nhibernate and linq to nhibernate to simply make a linq call to the database and get back an array of objects...
Jason
Then I would focus your energy on that area of your code, rather than the decorator pattern or conversion. That's just the tip of the iceberg. Use a profiler to find out what's going on. I believe Ayende Rahien has an NHibernate profiler, but I haven't used it myself.
Drew Noakes