Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ViewModel decrease web apps performace

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.

like image 457
BobRock Avatar asked Oct 08 '22 17:10

BobRock


2 Answers

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.

like image 193
Darin Dimitrov Avatar answered Oct 10 '22 06:10

Darin Dimitrov


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.

like image 32
Oskar Berggren Avatar answered Oct 10 '22 05:10

Oskar Berggren