的ASP.NET MVC的视图模型应该是类或结构? [英] Asp .Net MVC Viewmodel should be class or struct?

查看:98
本文介绍了的ASP.NET MVC的视图模型应该是类或结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚才一直在想,我们在asp.net MVC创建视图模型对象的概念。我们的目的是实例并从控制器,通过它可以查看和浏览阅读和显示数据。

I have just been thinking about the concept of view model object we create in asp.net MVC. Our purpose is to instantiate it and pass it from controller to view and view read it and display the data.

这些视图模型通常是通过构造函数实例。我们不会需要初始化成员,我们可能并不需要重新定义/覆盖参数的构造函数,我们并不需要继承特性存在。

Those view model are usually instantiated through constructor. We won't need to initialize the members, we may not need to redefine/override parameterless constructor and we don't need inheritance feature there.

那么,我们为什么不使用结构类型,我们认为模型来代替类。这将提高性能。

So, why don't we use struct type for our view model instead of class. It will enhance the performance.

推荐答案

您拿这将提升业绩为一个给定的,但你真的确定吗?结构进行比的非常具体的情况下更好地类。我概括为简单起见,但是场景主要是:

You take "it will enhance the performance" as a given, but are you really sure about this? Structs perform better than classes in very specific circumstances. I'm generalizing for simplicity, but the scenarios chiefly are:


  • 他们是不可改变的。

  • 它们很小,例如一般不超过3 - 4场

  • 您正在生成的的人(通常是百万或更多)在极短的时间跨度。

  • 您正在与他们合作的紧密循环。

  • ,他们通过旅游的code路径,这些具体的结构优化,不执行装箱/拆箱操作。

  • They're immutable.
  • They're small, e.g. usually no more than 3 - 4 fields.
  • You're generating tons (often millions or more) of them over an extremely short time span.
  • You're working with them in tight loops.
  • The code paths that they travel through are optimized for those specific structs and do not perform boxing / unboxing operations.

有别人,但是这只是从我的头顶。即使如此,我们正在谈论的往往微不足道的性能提升。正如微秒的微不足道。

There are others, but that's just off the top of my head. And even then, we're talking about often minuscule performance gains. As in microseconds minuscule.

即使你能保证你的视图模型是不可变的很小,其他条件不成立。假设每个请求一个视图模型,您的Web服务器是不会处理数百万每秒的请求。此外,MVC框架不与这些在密集的循环工作,不包含这个特殊的结构优化code路径。 MVC框架最终会在你的值类型执行万吨装箱/拆箱操作的结果。

Even if you can guarantee that your view models are immutable and tiny, the other conditions don't hold. Assuming one view model per request, your web server is not going to handle millions of requests per second. Furthermore, the MVC framework does not work with these in tight loops and does not contain code paths optimized for this particular struct. The MVC framework will end up performing tons of boxing / unboxing operations on your value types as a result.

底线 - 不要微优化或过度设计的解决方案。类是就好了。和优化而言,当,经常测量,以确保你投入你的时间是值得的风险。当有更大的鱼炒不与理会琐事

Bottom line - don't micro-optimize or over-engineer your solution. Classes are just fine. And when optimization is concerned, always measure to make sure you're devoting your time to a worthwhile venture. Don't bother with trivialities when there are bigger fish to fry.

这篇关于的ASP.NET MVC的视图模型应该是类或结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆