Do I Use Multiple First() or First() once?

Posts   
 
    
NickD
User
Posts: 224
Joined: 31-Jan-2005
# Posted on: 11-Jun-2010 22:51:57   

LLBLGen 2.6

I've got a situation where I want to pull multiple property values from a single entity stored in an IEnumerable. First, let's fill up the enumerable collection:

IEnumerable<ActionTaskEntity> actions = FetchActionsFromDatabase();

...now, I want to display the timestamp and user who performed that action in a web page. So, I can now do multiple First() fetches:

string displayString = string.Format("Page Viewed at {0} by {1}", actions.First().ActionDate, actions.First().ActionUser); 

...or I could fetch back into the LLBLGen entity and use that:

ActionTaskEntity action = actions.First();
string displayString = string.Format("Page Viewed at {0} by {1}", action.ActionDate, action.ActionUser);

...now, I fully understand that in this example there is probably not very much difference at all between the two, but as we all understand, multiplied over time and for multiple users, it could make a difference. And, even if only using the "First" function twice is not enough, what if I used it five times in one string building operation? What about 10? When does it suddenly make a difference?

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 12-Jun-2010 02:11:45   

The question is What FetchActionsFromDatabase return? If it already fetch from database, then your next First calls is simply LINQ2Objects. What is the SQL you want to achieve, and what is the code inside FetchActionsFromDatabase?

David Elizondo | LLBLGen Support Team
NickD
User
Posts: 224
Joined: 31-Jan-2005
# Posted on: 14-Jun-2010 16:12:28   

For this discussion, that is not important. I'm more interested (and so therefore this is a LINQ question and perhaps this is the wrong place for this discussion) in whether using .First() multiple times is just as fast as filling an object once and then fetching the properties from that object.

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 15-Jun-2010 09:33:10   

I'm not sure if calling First() multiple times migh hurt the performance, but it's supposed to have some effect what so ever.

So calling it once into an entity object that can be used on multiple occasions seems the best thing to do.

Which also seems like the best code refactoring you can do in this case. You should not call the same method multiple times using the same parameters if you know the output will always be the same, instead save the returned result and use it many times afterwards.

At least if you ever want to pick the last entity instead of the first, you will have one line of code to change.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39903
Joined: 17-Aug-2003
# Posted on: 15-Jun-2010 09:57:27   

I said something stupidflushed

Frans Bouma | Lead developer LLBLGen Pro