java - FileInputStream读取方法的风格

标签 java coding-style

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.

最佳答案

第一种形式允许您在多次执行中重复使用相同的byte[] 数组。基本上,您可以读取产生最少垃圾(低 GC Activity )的整个流。

后者显然更方便,但每次在 read() 方法内部执行时都需要创建 byte[] 的新实例。这意味着在读取 10 GiB 文件(即使是 100 字节 block )时,您的应用程序将总共分配 10 GiB 内存 - 不是同时分配,但垃圾收集器仍然会疯狂工作。

看看Collection.toArray(T[]) - 它遵循相同的原则。

关于java - FileInputStream读取方法的风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9456454/

相关文章:

java - 函数式java - 通过调用成员函数进行转换

java - 检查 Android 中的有效手机号码

php - 对应的restful PHP函数有没有标准?

Excel-VBA : Variable Names, 匈牙利符号和变量命名最佳实践

c# - 代码格式样式 - 哪一种更可取

scala - 如果定义了选项,则用于在链中应用函数的惯用 Scala

java - 调整 Swing 部件的位置

java - Wicket 从 Web 应用程序目录外部的文件系统创建图像

java - 为什么不能以编程方式滚动 ScrollView?

Ruby:将两个相似的方法合并为一个?