为什么写在块到流? [英] Why write to Stream in chunks?

查看:158
本文介绍了为什么写在块到流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很奇怪,为什么这样的例子很多读取字节数组入夹头流,而不是一次全部...我知道这是一个软的问题,但我很感兴趣。

I am wondering why so many examples read byte arrays into streams in chucks and not all at once... I know this is a soft question, but I am interested.

我了解一点的硬件和填充缓冲区可以很依赖的大小,你会不会想再次写入缓冲区,直到它被刷新到任何地方需要去等...但与.Net平台(和其他现代语言),我看到两个例子。因此,当使用它时,或者是第二绝对没有任何

I understand a bit about hardware and filling buffers can be very size dependent and you wouldn't want to write to the buffer again until it has been flushed to wherever it needs to go etc... but with the .Net platform (and other modern languages) I see examples of both. So when use which and when, or is the second an absolute no no?

下面是事情(代码)我的意思是:

Here is the thing (code) I mean:

var buffer = new byte[4096];

while (true)
{
    var read = this.InputStream.Read(buffer, 0, buffer.Length);

    if (read == 0)
        break;

    OutputStream.Write(buffer, 0, read);
}



而不是:

rather than:

var buffer = new byte[InputStream.Length];

var read = this.InputStream.Read(buffer, 0, buffer.Length);

OutputStream.Write(buffer, 0, read);



相信无论是合法的?那么,为什么要经过while循环大惊小怪(不论你决定来构建它)?

I believe both are legal? So why go through all the fuss of the while loop (in whatever for you decide to structure it)?

我玩鬼子在这里提倡,因为我想学习尽可能多我可以:)

I am playing devils advocate here as I want to learn as much as I can :)

推荐答案

在第一种情况下,你需要的是内存4kB的。在第二种情况下,你作为输入数据流需要需要尽可能多的内存。如果输入流为4GB,你需要4GB。

In the first case, all you need is 4kB of memory. In the second case, you need as much memory as the input stream data takes. If the input stream is 4GB, you need 4GB.

你觉得如果需要4GB内存文件复制操作这将是很好?如果你有准备,这是一个磁盘映像20GB?

Do you think it would be good if a file copy operation required 4GB of RAM? What if you were to prepare a disk image that's 20GB?

还有这事与管道。你不经常使用它们在Windows,但类似案件往往被其他操作系统。第二种情况等待读取所有数据,然后才将它们写入到输出。但是,有时最好是尽早,第一种情况下将尽快输入的第一4kB的读出开始写入到输出流写入数据。想想网页服务的:它是可取的Web服务器,以尽快发送数据,使客户端的Web浏览器将开始渲染标题和内容的第一部分,而不是等待整个身体

There is also this thing with pipes. You don't often use them on Windows, but a similar case is often seen on other operating systems. The second case waits for all data to be read, and only then writes them to the output. However, sometimes it is advisable to write data as soon as possible—the first case will start writing to the output stream as soon as the first 4kB of input is read. Think of serving web pages: it is advisable for a web server to send data as soon as possible, so that client's web browser will start rendering headers and first part of the content, not waiting for the whole body.

不过,如果你知道的输入流不会超过4KB大,那么这两种情况下是相同的。

However, if you know that the input stream won't be bigger than 4kB, then both cases are equivalent.

这篇关于为什么写在块到流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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