使用单案例区分联合类型是否会对性能产生影响? [英] Does using single-case discriminated union types have implications on performance?

查看:83
本文介绍了使用单案例区分联合类型是否会对性能产生影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个原始值都有一个包装器是很不错的,这样就没有办法滥用它.我怀疑这种便利是有代价的.有性能下降吗?如果您担心性能,我应该使用裸露的原始值代替吗?

It is nice to have a wrapper for every primitive value, so that there is no way to misuse it. I suspect this convenience comes at a price. Is there a performance drop? Should I rather use bare primitive values instead if the performance is a concern?

推荐答案

是的,使用单格联合类型包装原始值时,性能将会下降.联合案例被编译到类中,因此您将付出分配(后来收集)类的代价,并且每次获取联合案例中持有的值时,您还将有一个附加的间接寻址.

Yes, there's going to be a performance drop when using single-case union types to wrap primitive values. Union cases are compiled into classes, so you'll pay the price of allocating (and later, collecting) the class and you'll also have an additional indirection each time you fetch the value held inside the union case.

根据应用程序的具体情况以及产生这些额外开销的频率,如果它可以使您的代码更安全,更模块化,那么仍然值得这样做.

Depending on the specifics of your application, and how often you'll incur these additional overheads, it may still be worth doing if it makes your code safer and more modular.

我已经用F#编写了对性能敏感的代码很多,而我个人的喜好是尽可能使用F#度量单位类型来标记"原始类型(例如,整数) ).这可以防止它们被滥用(由于F#编译器的类型检查器),而且还避免了任何额外的运行时开销,因为在编译代码时会删除度量类型.如果您需要一些示例,我在 fsharp-tools中广泛使用了这种设计模式 项目.

I've written a lot of performance-sensitive code in F#, and my personal preference is to use F# unit-of-measure types whenever possible to "tag" primitive types (e.g., ints). This keeps them from being misused (thanks to the F# compiler's type checker) but also avoids any additional run-time overhead, since the measure types are erased when the code is compiled. If you want some examples of this, I've used this design pattern extensively in my fsharp-tools projects.

这篇关于使用单案例区分联合类型是否会对性能产生影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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