Asp .Net MVC Viewmodel 应该是类还是结构? [英] Asp .Net MVC Viewmodel should be class or struct?

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

问题描述

我刚刚在思考我们在 asp.net MVC 中创建的视图模型对象的概念.我们的目的是将它实例化并从控制器传递给view和view读取并显示数据.

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 个字段.
  • 您在极短的时间内生成了(通常是数百万或更多).
  • 您与他们紧密合作.
  • 它们经过的代码路径针对这些特定结构进行了优化,并且不执行装箱/拆箱操作.
  • 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 框架不能在紧密循环中使用这些,并且不包含针对此特定结构优化的代码路径.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 Viewmodel 应该是类还是结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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