Field Members vs Method Variables?
- by Braveyard
Recently I've been thinking about performance difference between class field members and method variables. What exactly I mean is in the example below :
Lets say we have a DataContext object for Linq2SQL
class DataLayer
{
ProductDataContext context = new ProductDataContext();
public IQueryable<Product> GetData()
{
return context.Where(t=>t.ProductId == 2);
}
}
In the example above, context will be stored in heap and the GetData method variables will be removed from Stack after Method is executed.
So lets examine the following example to make a distinction :
class DataLayer
{
public IQueryable<Product> GetData()
{
ProductDataContext context = new ProductDataContext();
return context.Where(t=>t.ProductId == 2);
}
}
(*1) So okay first thing we know is if we define ProductDataContext instance as a field, we can reach it everywhere in the class which means we don't have to create same object instance all the time.
But lets say we are talking about Asp.NET and once the users press submit button the post data is sent to the server and the events are executed and the posted data stored in a database via the method above so it is probable that the same user can send different data after one another.If I know correctly after the page is executed, the finalizers come into play and clear things from memory (from heap) and that means we lose our instance variables from memory as well and after another post, DataContext should be created once again for the new page cycle.
So it seems the only benefit of declaring it publicly to the whole class is the just number one text above.
Or is there something other?
Thanks in advance...
(If I told something incorrect please fix me.. )