花1K內存實現高效I/O的RandomAccessFile類
通過擴展RandomAccessFile類使之具備Buffer改善I/O性能
簡介: JAVA的文件隨機存取類(RandomAccessFile)的I/O效率較低。通過分析其中原因,提出解決方案。逐步展示如何創建具備緩存讀寫能力的文件隨機存取類,並進行了優化。通過與其它文件訪問類的性能對比,證明了其實用價值。
目前最流行的J2SDK版本是1.3系列。使用該版本的開發人員需文件隨機存取,就得使用RandomAccessFile類。其I/O性能較之其它常用開發語言的同類性能差距甚遠,嚴重影響程序的運行效率。
開發人員迫切需要提高效率,下面分析RandomAccessFile等文件類的源代碼,找出其中的癥結所在,並加以改進優化,創建一個"性/價比"俱佳的隨機文件訪問類BufferedRandomAccessFile。
在改進之前先做一個基本測試:逐字節COPY一個12兆的文件(這裏牽涉到讀和寫)。
讀 | 寫 | 耗用時間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream + DataInputStream | BufferedOutputStream + DataOutputStream | 2.935 |
我們可以看到兩者差距約32倍,RandomAccessFile也太慢了。先看看兩者關鍵部分的源代碼,對比分析,找出原因。
1.1.[RandomAccessFile]
public class RandomAccessFile implements DataOutput, DataInput { public final byte readByte() throws IOException { int ch = this.read(); if (ch < 0) throw new EOFException(); return (byte)(ch); } public native int read() throws IOException; public final void writeByte(int v) throws IOException { write(v); } public native void write(int b) throws IOException; } |
可見,RandomAccessFile每讀/寫一個字節就需對磁盤進行一次I/O操作。
1.2.[BufferedInputStream]
public class BufferedInputStream extends FilterInputStream { private static int defaultBufferSize = 2048; protected byte buf[]; // 建立讀緩存區 public BufferedInputStream(InputStream in, int size) { super(in); if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buf = new byte[size]; } public synchronized int read() throws IOException { ensureOpen(); if (pos >= count) { fill(); if (pos >= count) return -1; } return buf[pos++] & 0xff; // 直接從BUF[]中讀取 } private void fill() throws IOException { if (markpos < 0) pos = 0; /* no mark: throw away the buffer */ else if (pos >= buf.length) /* no room left in buffer */ if (markpos > 0) { /* can throw away early part of the buffer */ int sz = pos - markpos; System.arraycopy(buf, markpos, buf, 0, sz); pos = sz; markpos = 0; } else if (buf.length >= marklimit) { markpos = -1; /* buffer got too big, invalidate mark */ pos = 0; /* drop buffer contents */ } else { /* grow buffer */ int nsz = pos * 2; if (nsz > marklimit) nsz = marklimit; byte nbuf[] = new byte[nsz]; System.arraycopy(buf, 0, nbuf, 0, pos); buf = nbuf; } count = pos; int n = in.read(buf, pos, buf.length - pos); if (n > 0) count = n + pos; } } |
1.3.[BufferedOutputStream]
public class BufferedOutputStream extends FilterOutputStream { protected byte buf[]; // 建立寫緩存區 public BufferedOutputStream(OutputStream out, int size) { super(out); if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buf = new byte[size]; } public synchronized void write(int b) throws IOException { if (count >= buf.length) { flushBuffer(); } buf[count++] = (byte)b; // 直接從BUF[]中讀取 } private void flushBuffer() throws IOException { if (count > 0) { out.write(buf, 0, count); count = 0; } } } |
可見,Buffered I/O putStream每讀/寫一個字節,若要操作的數據在BUF中,就直接對內存的buf[]進行讀/寫操作;否則從磁盤相應位置填充buf[],再直接對內存的buf[]進行讀/寫操作,絕大部分的讀/寫操作是對內存buf[]的操作。
1.3.小結
內存存取時間單位是納秒級(10E-9),磁盤存取時間單位是毫秒級(10E-3),同樣操作一次的開銷,內存比磁盤快了百萬倍。理論上可以預見,即使對內存操作上萬次,花費的時間也遠少對於磁盤一次I/O的開銷。顯然後者是通過增加位於內存的BUF存取,減少磁盤I/O的開銷,提高存取效率的,當然這樣也增加了BUF控制部分的開銷。從實際應用來看,存取效率提高了32倍。
根據1.3得出的結論,現試着對RandomAccessFile類也加上緩衝讀寫機制。
隨機訪問類與順序類不同,前者是通過實現DataInput/DataOutput接口創建的,而後者是擴展FilterInputStream/FilterOutputStream創建的,不能直接照搬。
2.1.開闢緩衝區BUF[默認:1024字節],用作讀/寫的共用緩衝區。
2.2.先實現讀緩衝。
讀緩衝邏輯的基本原理:
A 欲讀文件POS位置的一個字節。
B 查BUF中是否存在?若有,直接從BUF中讀取,並返回該字符BYTE。
C 若沒有,則BUF重新定位到該POS所在的位置並把該位置附近的BUFSIZE的字節的文件內容填充BUFFER,返回B。
以下給出關鍵部分代碼及其說明:
public class BufferedRandomAccessFile extends RandomAccessFile { // byte read(long pos):讀取當前文件POS位置所在的字節 // bufstartpos、bufendpos代表BUF映射在當前文件的首/尾偏移地址。 // curpos指當前類文件指針的偏移地址。 public byte read(long pos) throws IOException { if (pos < this.bufstartpos || pos > this.bufendpos ) { this.flushbuf(); this.seek(pos); if ((pos < this.bufstartpos) || (pos > this.bufendpos)) throw new IOException(); } this.curpos = pos; return this.buf[(int)(pos - this.bufstartpos)]; } // void flushbuf():bufdirty爲真,把buf[]中尚未寫入磁盤的數據,寫入磁盤。 private void flushbuf() throws IOException { if (this.bufdirty == true) { if (super.getFilePointer() != this.bufstartpos) { super.seek(this.bufstartpos); } super.write(this.buf, 0, this.bufusedsize); this.bufdirty = false; } } // void seek(long pos):移動文件指針到pos位置,並把buf[]映射填充至POS 所在的文件塊。 public void seek(long pos) throws IOException { if ((pos < this.bufstartpos) || (pos > this.bufendpos)) { // seek pos not in buf this.flushbuf(); if ((pos >= 0) && (pos <= this.fileendpos) && (this.fileendpos != 0)) { // seek pos in file (file length > 0) this.bufstartpos = pos * bufbitlen / bufbitlen; this.bufusedsize = this.fillbuf(); } else if (((pos == 0) && (this.fileendpos == 0)) || (pos == this.fileendpos + 1)) { // seek pos is append pos this.bufstartpos = pos; this.bufusedsize = 0; } this.bufendpos = this.bufstartpos + this.bufsize - 1; } this.curpos = pos; } // int fillbuf():根據bufstartpos,填充buf[]。 private int fillbuf() throws IOException { super.seek(this.bufstartpos); this.bufdirty = false; return super.read(this.buf); } } |
至此緩衝讀基本實現,逐字節COPY一個12兆的文件(這裏牽涉到讀和寫,用BufferedRandomAccessFile試一下讀的速度):
讀 | 寫 | 耗用時間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedRandomAccessFile | BufferedOutputStream +DataOutputStream | 2.813 |
BufferedInputStream +DataInputStream | BufferedOutputStream +DataOutputStream | 2.935 |
可見速度顯著提高,與BufferedInputStream+DataInputStream不相上下。
2.3.實現寫緩衝。
寫緩衝邏輯的基本原理:
A欲寫文件POS位置的一個字節。
B 查BUF中是否有該映射?若有,直接向BUF中寫入,並返回true。
C若沒有,則BUF重新定位到該POS所在的位置,並把該位置附近的BUFSIZE字節的文件內容填充BUFFER,返回B。
下面給出關鍵部分代碼及其說明:
// boolean write(byte bw, long pos):向當前文件POS位置寫入字節BW。 // 根據POS的不同及BUF的位置:存在修改、追加、BUF中、BUF外等情 況。在邏輯判斷時,把最可能出現的情況,最先判斷,這樣可提高速度。 // fileendpos:指示當前文件的尾偏移地址,主要考慮到追加因素 public boolean write(byte bw, long pos) throws IOException { if ((pos >= this.bufstartpos) && (pos <= this.bufendpos)) { // write pos in buf this.buf[(int)(pos - this.bufstartpos)] = bw; this.bufdirty = true; if (pos == this.fileendpos + 1) { // write pos is append pos this.fileendpos++; this.bufusedsize++; } } else { // write pos not in buf this.seek(pos); if ((pos >= 0) && (pos <= this.fileendpos) && (this.fileendpos != 0)) { // write pos is modify file this.buf[(int)(pos - this.bufstartpos)] = bw; } else if (((pos == 0) && (this.fileendpos == 0)) || (pos == this.fileendpos + 1)) { // write pos is append pos this.buf[0] = bw; this.fileendpos++; this.bufusedsize = 1; } else { throw new IndexOutOfBoundsException(); } this.bufdirty = true; } this.curpos = pos; return true; } |
至此緩衝寫基本實現,逐字節COPY一個12兆的文件,(這裏牽涉到讀和寫,結合緩衝讀,用BufferedRandomAccessFile試一下讀/寫的速度):
讀 | 寫 | 耗用時間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream +DataInputStream | BufferedOutputStream +DataOutputStream | 2.935 |
BufferedRandomAccessFile | BufferedOutputStream +DataOutputStream | 2.813 |
BufferedRandomAccessFile | BufferedRandomAccessFile | 2.453 |
可見綜合讀/寫速度已超越BufferedInput/OutputStream+DataInput/OutputStream。
優化原則:
- 調用頻繁的語句最需要優化,且優化的效果最明顯。
- 多重嵌套邏輯判斷時,最可能出現的判斷,應放在最外層。
- 減少不必要的NEW。
這裏舉一典型的例子:
public void seek(long pos) throws IOException { ... this.bufstartpos = pos * bufbitlen / bufbitlen; // bufbitlen指buf[]的位長,例:若bufsize=1024,則bufbitlen=10。 ... } |
seek函數使用在各函數中,調用非常頻繁,上面加重的這行語句根據pos和bufsize確定buf[]對應當前文件的映射位置,用"*"、"/"確定,顯然不是一個好方法。
優化一:this.bufstartpos = (pos << bufbitlen) >> bufbitlen;
優化二:this.bufstartpos = pos & bufmask;// this.bufmask = ~((long)this.bufsize - 1);
兩者效率都比原來好,但後者顯然更好,因爲前者需要兩次移位運算、後者只需一次邏輯與運算(bufmask可以預先得出)。
至此優化基本實現,逐字節COPY一個12兆的文件,(這裏牽涉到讀和寫,結合緩衝讀,用優化後BufferedRandomAccessFile試一下讀/寫的速度):
讀 | 寫 | 耗用時間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream +DataInputStream | BufferedOutputStream +DataOutputStream | 2.935 |
BufferedRandomAccessFile | BufferedOutputStream +DataOutputStream | 2.813 |
BufferedRandomAccessFile | BufferedRandomAccessFile | 2.453 |
BufferedRandomAccessFile優 | BufferedRandomAccessFile優 | 2.197 |
可見優化儘管不明顯,還是比未優化前快了一些,也許這種效果在老式機上會更明顯。
以上比較的是順序存取,即使是隨機存取,在絕大多數情況下也不止一個BYTE,所以緩衝機制依然有效。而一般的順序存取類要實現隨機存取就不怎麼容易了。
提供文件追加功能:
public boolean append(byte bw) throws IOException { return this.write(bw, this.fileendpos + 1); } |
提供文件當前位置修改功能:
public boolean write(byte bw) throws IOException { return this.write(bw, this.curpos); } |
返回文件長度(由於BUF讀寫的原因,與原來的RandomAccessFile類有所不同):
public long length() throws IOException { return this.max(this.fileendpos + 1, this.initfilelen); } |
返回文件當前指針(由於是通過BUF讀寫的原因,與原來的RandomAccessFile類有所不同):
public long getFilePointer() throws IOException { return this.curpos; } |
提供對當前位置的多個字節的緩衝寫功能:
public void write(byte b[], int off, int len) throws IOException { long writeendpos = this.curpos + len - 1; if (writeendpos <= this.bufendpos) { // b[] in cur buf System.arraycopy(b, off, this.buf, (int)(this.curpos - this.bufstartpos), len); this.bufdirty = true; this.bufusedsize = (int)(writeendpos - this.bufstartpos + 1); } else { // b[] not in cur buf super.seek(this.curpos); super.write(b, off, len); } if (writeendpos > this.fileendpos) this.fileendpos = writeendpos; this.seek(writeendpos+1); } public void write(byte b[]) throws IOException { this.write(b, 0, b.length); } |
提供對當前位置的多個字節的緩衝讀功能:
public int read(byte b[], int off, int len) throws IOException { long readendpos = this.curpos + len - 1; if (readendpos <= this.bufendpos && readendpos <= this.fileendpos ) { // read in buf System.arraycopy(this.buf, (int)(this.curpos - this.bufstartpos), b, off, len); } else { // read b[] size > buf[] if (readendpos > this.fileendpos) { // read b[] part in file len = (int)(this.length() - this.curpos + 1); } super.seek(this.curpos); len = super.read(b, off, len); readendpos = this.curpos + len - 1; } this.seek(readendpos + 1); return len; } public int read(byte b[]) throws IOException { return this.read(b, 0, b.length); } public void setLength(long newLength) throws IOException { if (newLength > 0) { this.fileendpos = newLength - 1; } else { this.fileendpos = 0; } super.setLength(newLength); } public void close() throws IOException { this.flushbuf(); super.close(); } |
至此完善工作基本完成,試一下新增的多字節讀/寫功能,通過同時讀/寫1024個字節,來COPY一個12兆的文件,(這裏牽涉到讀和寫,用完善後BufferedRandomAccessFile試一下讀/寫的速度):
讀 | 寫 | 耗用時間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream +DataInputStream | BufferedOutputStream +DataOutputStream | 2.935 |
BufferedRandomAccessFile | BufferedOutputStream +DataOutputStream | 2.813 |
BufferedRandomAccessFile | BufferedRandomAccessFile | 2.453 |
BufferedRandomAccessFile優 | BufferedRandomAccessFile優 | 2.197 |
BufferedRandomAccessFile完 | BufferedRandomAccessFile完 | 0.401 |
與JDK1.4新類MappedByteBuffer+RandomAccessFile的對比?
JDK1.4提供了NIO類 ,其中MappedByteBuffer類用於映射緩衝,也可以映射隨機文件訪問,可見JAVA設計者也看到了RandomAccessFile的問題,並加以改進。怎麼通過MappedByteBuffer+RandomAccessFile拷貝文件呢?下面就是測試程序的主要部分:
RandomAccessFile rafi = new RandomAccessFile(SrcFile, "r"); RandomAccessFile rafo = new RandomAccessFile(DesFile, "rw"); FileChannel fci = rafi.getChannel(); FileChannel fco = rafo.getChannel(); long size = fci.size(); MappedByteBuffer mbbi = fci.map(FileChannel.MapMode.READ_ONLY, 0, size); MappedByteBuffer mbbo = fco.map(FileChannel.MapMode.READ_WRITE, 0, size); long start = System.currentTimeMillis(); for (int i = 0; i < size; i++) { byte b = mbbi.get(i); mbbo.put(i, b); } fcin.close(); fcout.close(); rafi.close(); rafo.close(); System.out.println("Spend: "+(double)(System.currentTimeMillis()-start) / 1000 + "s"); |
試一下JDK1.4的映射緩衝讀/寫功能,逐字節COPY一個12兆的文件,(這裏牽涉到讀和寫):
讀 | 寫 | 耗用時間(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream +DataInputStream | BufferedOutputStream +DataOutputStream | 2.935 |
BufferedRandomAccessFile | BufferedOutputStream +DataOutputStream | 2.813 |
BufferedRandomAccessFile | BufferedRandomAccessFile | 2.453 |
BufferedRandomAccessFile優 | BufferedRandomAccessFile優 | 2.197 |
BufferedRandomAccessFile完 | BufferedRandomAccessFile完 | 0.401 |
MappedByteBuffer+RandomAccessFile | MappedByteBuffer+RandomAccessFile | 1.209 |
確實不錯,看來JDK1.4比1.3有了極大的進步。如果以後採用1.4版本開發軟件時,需要對文件進行隨機訪問,建議採用MappedByteBuffer+RandomAccessFile的方式。但鑑於目前採用JDK1.3及以前的版本開發的程序佔絕大多數的實際情況,如果您開發的JAVA程序使用了RandomAccessFile類來隨機訪問文件,並因其性能不佳,而擔心遭用戶詬病,請試用本文所提供的BufferedRandomAccessFile類,不必推翻重寫,只需IMPORT 本類,把所有的RandomAccessFile改爲BufferedRandomAccessFile,您的程序的性能將得到極大的提升,您所要做的就這麼簡單。
讀者可在此基礎上建立多頁緩存及緩存淘汰機制,以應付對隨機訪問強度大的應用。
SUN JDK1.3/1.4 SRC。
崔志翔,上海頤東網絡信息有限公司產品部經理,從事軟件產品開發。您可以通過E-mail: [email protected]與他取得聯繫。