使用unsafePerformIO合适吗? [英] Use of unsafePerformIO appropriate?

查看:186
本文介绍了使用unsafePerformIO合适吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在使用 unsafePerformIO 允许只读的IO调用适合纯代码的非变化文件,否则会导致很多问题?


$ b $主要原因是因为我想将它们存储在容器中,例如,使它们成为 Ord 的实例,但我似乎无法想象如何在没有将IO调用封装在 unsafePerformIO 中。

解决方案

安全



以您所描述的方式使用 unsafePerformIO 不应导致任何问题。



拇指规则是:如果您使用 unsafePerformIO 来定义一个可以在Haskell中定义的函数,那么您可以安全地使用它。

在你的情况中,你基本上使用它来达到在代码中定义一些固定值的相同效果。也就是说,您可以将只读的不变文件包含在源代码中,但需要将大量数据保存在内存中。因此,您的使用是安全的。例如,如果您发明了一个利用固定的100MB数据表的素数测试,那么可以使用 unsafePerformIO 来访问包含它的不可变文件。这将交易代码纯度的性能(内存占用),而不会影响安全性。

适当性



由于 unsafePerformIO 确实是不安全的(证明程序安全的责任在你身上),它应该被视为最后的手段,并且绝对不是读取文件内容的默认方式。

很难理解您的案例是否真的证明了使用 unsafePerformIO 的理由。你应该更详细地描述你试图达到的目的。



我猜想,如果你的程序要读取文件并将其全部内容存储在内存中,那么你将不会从 unsafePerformIO 获得性能优势,而应该使用纯代码。


Is using unsafePerformIO to allow read-only IO calls to non-changing files in pure code appropriate or is it going to cause a lot of problems?

The main reason is because I'd like to store them in containers and for example, make them an instance of Ord, but I can't seem to imagine how to do that without wrapping IO calls in unsafePerformIO.

解决方案

On safety

Using unsafePerformIO in the way you describe should not cause any problems.

The thumb rule is: if you are using unsafePerformIO to define a function which could be defined without it in Haskell, then you are using it safely.

In your case, you essentially use it to achieve the same effect of defining some fixed values in your code. That is, you could just include your read-only non-changing files in your source code, at the cost of keeping the whole lot of data in memory. So your use is safe.

For example, if you invented a primality test which somehow exploits a fixed 100MB data table, then it would be alright to use unsafePerformIO to access an immutable file containing it. This would trade code purity for performance (memory footprint), without compromising safety.

On appropriateness

Since unsafePerformIO is indeed unsafe (the burden of proving the program safe is on you), it should be regarded as a last resort, and definitely not as the default way for reading a file's contents.

It's hard to understand whether your case really justifies using unsafePerformIO. You should describe what you are trying to achieve in more detail.

I'd guess that, if your program is going to read the files and store their whole contents in memory, then you would get no performance advantage from unsafePerformIO, and you should use pure code instead.

这篇关于使用unsafePerformIO合适吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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