2012-02-26 66 views
2

FileInputStream中讀出方法簽名(是正確的術語?) -風格的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. 

回答

4

第一種形式允許您重複使用相同的byte[]陣列進行多次執行。基本上你可以讀取生成最少垃圾的全部流(低GC活性)。

後者顯然更方便,但需要在read()方法內部每次執行內部時創建byte[]的新實例。這意味着在讀取10個GiB文件(即使是100字節的塊)時,應用程序總共會分配10吉比特的內存 - 而不是同時,但垃圾收集器仍然會像瘋狂一樣工作。

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

+0

後面的一個更方便嗎? – UnKnown 2016-03-29 09:01:44