Lazy I/O 有什么不好? [英] What's so bad about Lazy I/O?

查看:24
本文介绍了Lazy I/O 有什么不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我普遍听说生产代码应该避免使用 Lazy I/O.我的问题是,为什么?除了玩玩之外,还可以使用 Lazy I/O 吗?什么使替代方案(例如枚举器)更好?

I've generally heard that production code should avoid using Lazy I/O. My question is, why? Is it ever OK to use Lazy I/O outside of just toying around? And what makes the alternatives (e.g. enumerators) better?

推荐答案

懒惰 IO 的问题是释放您获得的任何资源都有些不可预测,因为这取决于您的程序如何使用数据——它的需求模式".一旦您的程序删除对资源的最后一个引用,GC 最终将运行并释放该资源.

Lazy IO has the problem that releasing whatever resource you have acquired is somewhat unpredictable, as it depends on how your program consumes the data -- its "demand pattern". Once your program drops the last reference to the resource, the GC will eventually run and release that resource.

惰性流是一种非常的编程风格.这就是 shell 管道如此有趣和流行的原因.

Lazy streams are a very convenient style to program in. This is why shell pipes are so fun and popular.

但是,如果资源受到限制(如在高性能场景中,或期望扩展到机器极限的生产环境),依靠 GC 清理可能是不够的保证.

However, if resources are constrained (as in high-performance scenarios, or production environments that expect to scale to the limits of the machine) relying on the GC to clean up can be an insufficient guarantee.

有时您必须急切地释放资源,以提高可扩展性.

Sometimes you have to release resources eagerly, in order to improve scalability.

那么,不意味着放弃增量处理(这又会消耗太多资源)的惰性 IO 的替代方法是什么?好吧,我们有基于 foldl 的处理,又名迭代器或枚举器,由 Oleg Kiselyov 在后期引入2000 年代,此后被许多基于网络的项目所普及.

So what are the alternatives to lazy IO that don't mean giving up on incremental processing (which in turn would consume too many resources)? Well, we have foldl based processing, aka iteratees or enumerators, introduced by Oleg Kiselyov in the late 2000s, and since popularized by a number of networking-based projects.

我们不是将数据作为惰性流处理,或者在一个大批量中处理数据,而是抽象基于块的严格处理,一旦读取最后一个块就保证资源的终结.这就是基于迭代器的编程的本质,它提供了非常好的资源约束.

Instead of processing data as lazy streams, or in one huge batch, we instead abstract over chunk-based strict processing, with guaranteed finalization of the resource once the last chunk is read. That's the essence of iteratee-based programming, and one that offers very nice resource constraints.

基于迭代的 IO 的缺点是它有一个有点笨拙的编程模型(大致类似于基于事件的编程,而不是基于线程的控制).在任何编程语言中,这绝对是一种先进的技术.而对于绝大多数的编程问题,lazy IO 完全可以满足.但是,如果您要打开许多文件,或在许多套接字上进行通信,或以其他方式同时使用许多资源,则迭代(或枚举器)方法可能更有意义.

The downside of iteratee-based IO is that it has a somewhat awkward programming model (roughly analogous to event-based programming, versus nice thread-based control). It is definitely an advanced technique, in any programming language. And for the vast majority of programming problems, lazy IO is entirely satisfactory. However, if you will be opening many files, or talking on many sockets, or otherwise using many simultaneous resources, an iteratee (or enumerator) approach might make sense.

这篇关于Lazy I/O 有什么不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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