国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

花1K內(nèi)存實(shí)現(xiàn)高效I/O的RandomAccessFile類

2019-11-18 15:08:10
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

  通過(guò)擴(kuò)展RandomaccessFile類使之具備Buffer改善I/O性能
java的文件隨機(jī)存取類(RandomAccessFile)的I/O效率較低。通過(guò)分析其中原因,提出解決方案。逐步展示如何創(chuàng)建具備緩存讀寫(xiě)能力的文件隨機(jī)存取類,并進(jìn)行了優(yōu)化。通過(guò)與其它文件訪問(wèn)類的性能對(duì)比,證實(shí)了其實(shí)用價(jià)值。
主體:

目前最流行的J2SDK版本是1.3系列。使用該版本的開(kāi)發(fā)人員需文件隨機(jī)存取,就得使用RandomAccessFile類。其I/O性能較之其它常用開(kāi)發(fā)語(yǔ)言的同類性能差距甚遠(yuǎn),嚴(yán)重影響程序的運(yùn)行效率。

開(kāi)發(fā)人員迫切需要提高效率,下面分析RandomAccessFile等文件類的源代碼,找出其中的癥結(jié)所在,并加以改進(jìn)優(yōu)化,創(chuàng)建一個(gè)"性/價(jià)比"俱佳的隨機(jī)文件訪問(wèn)類BufferedRandomAccessFile。

1.在改進(jìn)之前先做一個(gè)基本測(cè)試:逐字節(jié)COPY一個(gè)12兆的文件(這里牽涉到讀和寫(xiě))。

讀 寫(xiě) 耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935

我們可以看到兩者差距約32倍,RandomAccessFile也太慢了。先看看兩者要害部分的源代碼,對(duì)比分析,找出原因。

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;
}



可見(jiàn),RandomAccessFile每讀/寫(xiě)一個(gè)字節(jié)就需對(duì)磁盤(pán)進(jìn)行一次I/O操作。

1.2.[BufferedInputStream]

public class BufferedInputStream extends FilterInputStream {
PRivate static int defaultBufferSize = 2048;
protected byte buf[]; // 建立讀緩存區(qū)
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[]; // 建立寫(xiě)緩存區(qū)
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;
}
}
}



可見(jiàn),Buffered I/O putStream每讀/寫(xiě)一個(gè)字節(jié),若要操作的數(shù)據(jù)在BUF中,就直接對(duì)內(nèi)存的buf[]進(jìn)行讀/寫(xiě)操作;否則從磁盤(pán)相應(yīng)位置填充buf[],再直接對(duì)內(nèi)存的buf[]進(jìn)行讀/寫(xiě)操作,絕大部分的讀/寫(xiě)操作是對(duì)內(nèi)存buf[]的操作。

1.3.小結(jié)

內(nèi)存存取時(shí)間單位是納秒級(jí)(10E-9),磁盤(pán)存取時(shí)間單位是毫秒級(jí)(10E-3),同樣操作一次的開(kāi)銷,內(nèi)存比磁盤(pán)快了百萬(wàn)倍。理論上可以預(yù)見(jiàn),即使對(duì)內(nèi)存操作上萬(wàn)次,花費(fèi)的時(shí)間也遠(yuǎn)少對(duì)于磁盤(pán)一次I/O的開(kāi)銷。顯然后者是通過(guò)增加位于內(nèi)存的BUF存取,減少磁盤(pán)I/O的開(kāi)銷,提高存取效率的,當(dāng)然這樣也增加了BUF控制部分的開(kāi)銷。從實(shí)際應(yīng)用來(lái)看,存取效率提高了32倍。

2.根據(jù)1.3得出的結(jié)論,現(xiàn)試著對(duì)RandomAccessFile類也加上緩沖讀寫(xiě)機(jī)制。

隨機(jī)訪問(wèn)類與順序類不同,前者是通過(guò)實(shí)現(xiàn)DataInput/DataOutput接口創(chuàng)建的,而后者是擴(kuò)展FilterInputStream/FilterOutputStream創(chuàng)建的,不能直接照搬。

2.1.開(kāi)辟緩沖區(qū)BUF[默認(rèn):1024字節(jié)],用作讀/寫(xiě)的共用緩沖區(qū)。

2.2.先實(shí)現(xiàn)讀緩沖。

讀緩沖邏輯的基本原理:

A 欲讀文件POS位置的一個(gè)字節(jié)。

B 查BUF中是否存在?若有,直接從BUF中讀取,并返回該字符BYTE。

C 若沒(méi)有,則BUF重新定位到該P(yáng)OS所在的位置并把該位置四周的BUFSIZE的字節(jié)的文件內(nèi)容填充BUFFER,返回B。

以下給出要害部分代碼及其說(shuō)明:

public class BufferedRandomAccessFile extends RandomAccessFile {
// byte read(long pos):讀取當(dāng)前文件POS位置所在的字節(jié)
// bufstartpos、bufendpos代表BUF映射在當(dāng)前文件的首/尾偏移地址。
// curpos指當(dāng)前類文件指針的偏移地址。
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[]中尚未寫(xiě)入磁盤(pán)的數(shù)據(jù),寫(xiě)入磁盤(pán)。

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):移動(dòng)文件指針到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():根據(jù)bufstartpos,填充buf[]。
private int fillbuf() throws IOException {
super.seek(this.bufstartpos);
this.bufdirty = false;
return super.read(this.buf);
}
}



至此緩沖讀基本實(shí)現(xiàn),逐字節(jié)COPY一個(gè)12兆的文件(這里牽涉到讀和寫(xiě),用BufferedRandomAccessFile試一下讀的速度):

讀 寫(xiě) 耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935

可見(jiàn)速度顯著提高,與BufferedInputStream+DataInputStream不相上下。

2.3.實(shí)現(xiàn)寫(xiě)緩沖。

寫(xiě)緩沖邏輯的基本原理:

A欲寫(xiě)文件POS位置的一個(gè)字節(jié)。

B 查BUF中是否有該映射?若有,直接向BUF中寫(xiě)入,并返回true。

C若沒(méi)有,則BUF重新定位到該P(yáng)OS所在的位置,并把該位置四周的 BUFSIZE字節(jié)的文件內(nèi)容填充BUFFER,返回B。

下面給出要害部分代碼及其說(shuō)明:

// boolean write(byte bw, long pos):向當(dāng)前文件POS位置寫(xiě)入字節(jié)BW。
// 根據(jù)POS的不同及BUF的位置:存在修改、追加、BUF中、BUF外等情
況。在邏輯判定時(shí),把最可能出現(xiàn)的情況,最先判定,這樣可提高速度。
// fileendpos:指示當(dāng)前文件的尾偏移地址,主要考慮到追加因素
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;
}



至此緩沖寫(xiě)基本實(shí)現(xiàn),逐字節(jié)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫(xiě),結(jié)合緩沖讀,用BufferedRandomAccessFile試一下讀/寫(xiě)的速度):

讀 寫(xiě) 耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedRandomAccessFile BufferedRandomAccessFile 2.453

可見(jiàn)綜合讀/寫(xiě)速度已超越BufferedInput/OutputStream+DataInput/OutputStream。

3.優(yōu)化BufferedRandomAccessFile。

優(yōu)化原則:

調(diào)用頻繁的語(yǔ)句最需要優(yōu)化,且優(yōu)化的效果最明顯。
多重嵌套邏輯判定時(shí),最可能出現(xiàn)的判定,應(yīng)放在最外層。
減少不必要的NEW。
這里舉一典型的例子:

public void seek(long pos) throws IOException {
...
this.bufstartpos = pos * bufbitlen / bufbitlen;
// bufbitlen指buf[]的位長(zhǎng),例:若bufsize=1024,則bufbitlen=10。
...
}



seek函數(shù)使用在各函數(shù)中,調(diào)用非常頻繁,上面加重的這行語(yǔ)句根據(jù)pos和bufsize確定buf[]對(duì)應(yīng)當(dāng)前文件的映射位置,用"*"、"/"確定,顯然不是一個(gè)好方法。

優(yōu)化一:this.bufstartpos = (pos << bufbitlen) >> bufbitlen;

優(yōu)化二:this.bufstartpos = pos & bufmask; // this.bufmask = ~((long)this.bufsize - 1);

兩者效率都比原來(lái)好,但后者顯然更好,因?yàn)榍罢咝枰獌纱我莆贿\(yùn)算、后者只需一次邏輯與運(yùn)算(bufmask可以預(yù)先得出)。

至此優(yōu)化基本實(shí)現(xiàn),逐字節(jié)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫(xiě),結(jié)合緩沖讀,用優(yōu)化后BufferedRandomAccessFile試一下讀/寫(xiě)的速度):

讀 寫(xiě) 耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedRandomAccessFile BufferedRandomAccessFile 2.453
BufferedRandomAccessFile優(yōu) BufferedRandomAccessFile優(yōu) 2.197

可見(jiàn)優(yōu)化盡管不明顯,還是比未優(yōu)化前快了一些,也許這種效果在老式機(jī)上會(huì)更明顯。

以上比較的是順序存取,即使是隨機(jī)存取,在絕大多數(shù)情況下也不止一個(gè)BYTE,所以緩沖機(jī)制依然有效。而一般的順序存取類要實(shí)現(xiàn)隨機(jī)存取就不怎么輕易了。

4.需要完善的地方

提供文件追加功能:

public boolean append(byte bw) throws IOException {
return this.write(bw, this.fileendpos + 1);
}



提供文件當(dāng)前位置修改功能:

public boolean write(byte bw) throws IOException {
return this.write(bw, this.curpos);
}



返回文件長(zhǎng)度(由于BUF讀寫(xiě)的原因,與原來(lái)的RandomAccessFile類有所不同):

public long length() throws IOException {
return this.max(this.fileendpos + 1, this.initfilelen);
}



返回文件當(dāng)前指針(由于是通過(guò)BUF讀寫(xiě)的原因,與原來(lái)的RandomAccessFile類有所不同):

public long getFilePointer() throws IOException {
return this.curpos;
}



提供對(duì)當(dāng)前位置的多個(gè)字節(jié)的緩沖寫(xiě)功能:

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);
}



提供對(duì)當(dāng)前位置的多個(gè)字節(jié)的緩沖讀功能:

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();
}



至此完善工作基本完成,試一下新增的多字節(jié)讀/寫(xiě)功能,通過(guò)同時(shí)讀/寫(xiě)1024個(gè)字節(jié),來(lái)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫(xiě),用完善后BufferedRandomAccessFile試一下讀/寫(xiě)的速度):

讀 寫(xiě) 耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedRandomAccessFile BufferedRandomAccessFile 2.453
BufferedRandomAccessFile優(yōu) BufferedRandomAccessFile優(yōu) 2.197
BufferedRandomAccessFile完 BufferedRandomAccessFile完 0.401

5.與JDK1.4新類MappedByteBuffer+RandomAccessFile的對(duì)比?

JDK1.4提供了NIO類 ,其中MappedByteBuffer類用于映射緩沖,也可以映射隨機(jī)文件訪問(wèn),可見(jiàn)JAVA設(shè)計(jì)者也看到了RandomAccessFile的問(wèn)題,并加以改進(jìn)。怎么通過(guò)MappedByteBuffer+RandomAccessFile拷貝文件呢?下面就是測(cè)試程序的主要部分:

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的映射緩沖讀/寫(xiě)功能,逐字節(jié)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫(xiě)):

讀 寫(xiě) 耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedRandomAccessFile BufferedRandomAccessFile 2.453
BufferedRandomAccessFile優(yōu) BufferedRandomAccessFile優(yōu) 2.197
BufferedRandomAccessFile完 BufferedRandomAccessFile完 0.401
MappedByteBuffer+ RandomAccessFile MappedByteBuffer+ RandomAccessFile 1.209

確實(shí)不錯(cuò),看來(lái)JDK1.4比1.3有了極大的進(jìn)步。假如以后采用1.4版本開(kāi)發(fā)軟件時(shí),需要對(duì)文件進(jìn)行隨機(jī)訪問(wèn),建議采用MappedByteBuffer+RandomAccessFile的方式。但鑒于目前采用JDK1.3及以前的版本開(kāi)發(fā)的程序占絕大多數(shù)的實(shí)際情況,假如您開(kāi)發(fā)的JAVA程序使用了RandomAccessFile類來(lái)隨機(jī)訪問(wèn)文件,并因其性能不佳,而擔(dān)心遭用戶詬病,請(qǐng)?jiān)囉帽疚乃峁┑腂ufferedRandomAccessFile類,不必推翻重寫(xiě),只需IMPORT 本類,把所有的RandomAccessFile改為BufferedRandomAccessFile,您的程序的性能將得到極大的提升,您所要做的就這么簡(jiǎn)單。

6.未來(lái)的考慮

讀者可在此基礎(chǔ)上建立多頁(yè)緩存及緩存淘汰機(jī)制,以應(yīng)付對(duì)隨機(jī)訪問(wèn)強(qiáng)度大的應(yīng)用。

相關(guān)資源:

SUN JDK1.3/1.4 SRC。

關(guān)于作者
崔志翔,上海頤東網(wǎng)絡(luò)信息有限公司產(chǎn)品部經(jīng)理,從事軟件產(chǎn)品開(kāi)發(fā)。您可以通過(guò)E-mail:bladeinco@citiz.net 與他取得聯(lián)系。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 于都县| 聊城市| 兴国县| 鄂尔多斯市| 宣武区| 固镇县| 德州市| 措勤县| 灵寿县| 宁南县| 谷城县| 昌邑市| 东乡县| 阳曲县| 礼泉县| 黎川县| 洛浦县| 东海县| 建水县| 东乌珠穆沁旗| 普兰店市| 静海县| 伊春市| 富阳市| 边坝县| 连城县| 韶关市| 聂荣县| 微山县| 金堂县| 腾冲县| 静宁县| 云南省| 邵阳市| 泰安市| 泽库县| 达孜县| 正镶白旗| 博罗县| 尉犁县| 任丘市|