Question

As far as I can understand using view models can make web dev. life much easier, in sense that we can use this approach for display only needed properties in localized strings. Also I use in mvc3 view models jquery validation, etc.

Right now I'm in doubt since I have expirience real bottleneck in my webapp. with querying all objects (20 of them) like this

 List<Domain.Property> data = session.Query<Domain.Property>().ToList();    
 return PropertyViewModel.FromDomainModel(data);

and that list of Property objects are send to my ViewModel where is FromDomainModel which expects List of Property objects like this

List<PropertyViewModel> dataVm = new List<PropertyViewModel>();
{
            foreach (Property p in x)
            {
                dataVm.Add(new PropertyViewModel(p));
            }
            return dataVm;
}

now in same class I'm using

public PropertyViewModel(Property x)
        {
            Id = x.Id;
            Created = x.Created;
            Title = x.Title;
             ....
            Photo = x.Photos.First();
}

but using this approach sending collection of objects to viewmodel from where same viewmodel is returned with only few properties which I need, strangly (atleast for me) I expirience multiple entity load and duration time drastically increased.

If you need more info. please ask.

Also if you know for better solution please share.

Update: When using domain model I have 20Entities loaded and when using viewmodel described above 67 entities are loaded which dramatically decrease performanse.

Was it helpful?

Solution

There will indeed additional time spent in mapping between the domain models and the view models but this time will be ridiculously infinitesimally small that should absolutely not be any bottleneck. Calling a property setter in C# is an extremely fast operation and absolutely negligible compared to a database call for example.

So continue using view models without worrying that this would somehow affect the performance of your application.

OTHER TIPS

Different views will have different view models. If there is a large amount of data not needed by a view, it should not be included in the view model for that view.

Also check for select N+1 problems, and consider setting a batch size on classes and collections if you haven't already to make retrieval of referenced entities more efficient.

You shouldn't notice any bottleneck because of ViewModels instead it sounds like a performance problem with the calls to your database, the n+1 problem is a really common performance problem with ORMs, you should check the number of calls to your database. Entity Framework Profiler is a really nice debugger for EF, it will show you the number of calls to your database and if the performance is not good, it will suggest you how to improve it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top