麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

花1K內存實現高效I/O的RandomAccessFile類

2019-11-18 15:08:10
字體:
來源:轉載
供稿:網友

  通過擴展RandomaccessFile類使之具備Buffer改善I/O性能
java的文件隨機存取類(RandomAccessFile)的I/O效率較低。通過分析其中原因,提出解決方案。逐步展示如何創建具備緩存讀寫能力的文件隨機存取類,并進行了優化。通過與其它文件訪問類的性能對比,證實了其實用價值。
主體:

目前最流行的J2SDK版本是1.3系列。使用該版本的開發人員需文件隨機存取,就得使用RandomAccessFile類。其I/O性能較之其它常用開發語言的同類性能差距甚遠,嚴重影響程序的運行效率。

開發人員迫切需要提高效率,下面分析RandomAccessFile等文件類的源代碼,找出其中的癥結所在,并加以改進優化,創建一個"性/價比"俱佳的隨機文件訪問類BufferedRandomAccessFile。

1.在改進之前先做一個基本測試:逐字節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倍。

2.根據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。

3.優化BufferedRandomAccessFile。

優化原則:

調用頻繁的語句最需要優化,且優化的效果最明顯。
多重嵌套邏輯判定時,最可能出現的判定,應放在最外層。
減少不必要的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,所以緩沖機制依然有效。而一般的順序存取類要實現隨機存取就不怎么輕易了。

4.需要完善的地方

提供文件追加功能:

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

5.與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,您的程序的性能將得到極大的提升,您所要做的就這么簡單。

6.未來的考慮

讀者可在此基礎上建立多頁緩存及緩存淘汰機制,以應付對隨機訪問強度大的應用。

相關資源:

SUN JDK1.3/1.4 SRC。

關于作者
崔志翔,上海頤東網絡信息有限公司產品部經理,從事軟件產品開發。您可以通過E-mail:[email protected] 與他取得聯系。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 国内毛片视频 | 欧美电影在线观看 | 神马顶级推理片免费看 | 日韩在线欧美在线 | 日韩一级成人 | 国产精品欧美久久久久一区二区 | 中文字幕涩涩久久乱小说 | 成人毛片100免费观看 | 日本教室三级在线看 | 国产精品久久久久久久av | 午夜精品在线视频 | 国产精品久久久久久久不卡 | 欧美精品一区二区三区在线 | 永久免费在线观看av | 中韩毛片| 男女羞羞在线观看 | 91福利免费观看 | 日本欧美一区 | 黄色网址免费入口 | 国产精品av久久久久久久久久 | 欧美黄色性视频 | 日本精品视频一区二区三区四区 | 欧美巨乳在线观看 | 麻豆传传媒久久久爱 | 永久在线观看电影 | 午夜视频你懂的 | 一区二区久久精品66国产精品 | 4p一女两男做爰在线观看 | 国产精品视频1区 | 好骚综合在线 | 国产99视频精品免视看9 | 免费国产网站 | 国产免费观看视频 | 国产精品久久77777 | 亚洲一二区精品 | aa级黄色片 | 黄色av免费电影 | 黄色av电影在线播放 | 天天鲁在线视频免费观看 | 91毛片网站 | 黄网站免费在线看 |