Should Asp.Net MVC Viewmodel be a class or structure?

I just thought about the concept of the view model object that we create in asp.net MVC. Our goal is to create an instance and transfer it from the controller to view and view the read and display data.

This view model is usually created through the constructor. We do not need to initialize the elements, we may not need to redefine / redefine the constructor without parameters, and we do not need the inheritance function.

So, why don't we use the struct type for our view model instead of the class. This will increase productivity.

+6
asp.net-mvc
source share
2 answers

You think that "it will increase productivity" as a given, but are you really sure about that? Structures work better than classes in special circumstances. I generalize for simplicity, but in the main scenario:

  • They are unchanging.
  • They are small, for example. usually no more than 3-4 fields.
  • You generate tons (often millions or more) of them in a very short amount of time.
  • You work with them in hard cycles.
  • The code paths they move are optimized for these specific structures and do not perform boxing / unpacking operations.

There are others, but it's just out of my head. And even then we are talking about the often insignificant gain in productivity. As in microseconds minus.

Even if you can guarantee that your view models are immutable and tiny, other conditions are not preserved. Assuming one view model for each request, your web server will not process millions of requests per second. In addition, the MVC structure does not work with them in narrow loops and does not contain code paths optimized for this particular structure. As a result, the MVC framework will eventually perform many boxing / unpacking operations on your value types.

Bottom line - don't micro-optimize or rework your solution. Classes are great. And when optimizing, it always measures to make sure that you devote your time to a worthy enterprise. Do not worry about the little things when there is a big fish to fry.

+13
source share

use class. some presentation models require constructors, converters, and possibly more functionality, why limit the structure? (for example, if you have EF4 objects and you need to make POCO of them ...)

0
source share

All Articles