FileInputStream读取方法有签名(是正确的术语吗?) -
public int read(byte[] b) throws IOException
// Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.
// Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
像这样的签名有什么好处 -
public byte[] read(int numberOfBytes) throws IOException
// Reads up to numberOfBytes bytes of data from this input stream into an array of bytes.
// Returns- an array of bytes read. Array is empty if there is no more data because the end of the file has been reached.
答案 0 :(得分:4)
第一种形式允许您为多次执行重用相同的byte[]
数组。基本上你可以读取产生最小垃圾的整个流(低GC活动)。
后者显然更方便,但每次在byte[]
方法内部执行时都需要创建read()
的新实例。这意味着在读取10 GiB文件时(即使在100字节的块中),您的应用程序将总共分配10 GiB的内存 - 而不是同时,但垃圾收集器仍然会像疯了一样工作。
看看Collection.toArray(T[])
- 它遵循相同的原则。