0

在每次单独调用ObjectOutputStream#writeObject之后刷新 OutputStream比在一系列对象写入之后刷新流是否更有效?(例如:写入对象并刷新 4 次,或者写入 4 次然后仅刷新一次?)

ObjectOutputStream如何在内部工作?

4

3 回答 3

2

例如,发送四个Object[5](冲洗每个)是否比发送更好Object[20]

这不是更好。事实上,从性能的角度来看,它可能更糟。这些刷新中的每一个都将强制操作系统级别的 TCP/IP 堆栈“立即”发送数据。如果你最后只做一次刷新,你应该节省系统调用和网络流量。

如果您还没有这样做,BufferedOutputStream在 theSocket OutputStream和 the之间插入 aObjectOutputStream将对性能产生更大的影响。这允许序列化数据在写入套接字流之前在内存中累积。这可能会节省许多系统调用,并且可以将性能提高几个数量级……取决于发送的实际对象。

(四个Object[5]对象的表示大于一个Object[20]对象,这会在第一种情况下导致性能下降。但是,这最多是微不足道的,与刷新和缓冲问题相比,这是微不足道的。)

这个流在内部是如何工作的?

这是一个太笼统的问题,无法明智地回答。我建议你从这个页面上的文档开始阅读序列化。

于 2011-04-28T01:28:30.247 回答
1

If you look at the one and only public constructor of ObjectOutputStream, you note that it requires an underlying OutputStream for its instantiation.

When and how you flush your ObjectStream is entirely dependent on the type of stream you are using. (And in considering all this, do keep in mind that not all extension of OutputStream are guaranteed to respect your request to flush -- it is entirely implementation independent, as it is spelled out in the 'contract' of the javadocs.)

But certainly we can reason about it and even pull up the code and see what is actually done.

IFF the underlying OutputStream must utilize the OS services for devices (such as the disk or the network interface in case of Sockets) then the behavior of flush() is entirely OS dependent. For example, you may grab the output stream of a socket and then instantiate an ObjectOutputStream to write serialized objects to the net. TCP/IP implementation of the host OS is in charge.

What is more efficient?

Well, if your object stream is wrapping a ByteArrayOutputStream, you are potentially looking at a series of reallocs and System.arrayCopy() calls. I say potentially, since the implementation of byte array doubles the size on each (internal) resize() op and it is very unlikely that writing n (small) objects and flushing each time will result in n reallocs. (Where n is assumed to be a reasonably small number).

But if you are wrapping a network stream, you must keep in mind that network writes are very expensive. It makes much more sense, if your protocol allows it, to chunk your writes (to fill the send buffer) and just flush once.

于 2011-04-28T01:51:16.180 回答
1

不,这无关紧要,除非您有理由相信网络链接可能会断开,并且部分数据很有用。否则,这听起来像是一种无缘无故地让代码变得更复杂的方法。

于 2011-04-28T01:27:52.857 回答