有没有理由在下面选择a CharBuffer到a char[]:
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while( in.read(buf) >= 0 ) {
out.append( buf.flip() );
buf.clear();
}
Run Code Online (Sandbox Code Playgroud)
与
char[] buf = new char[DEFAULT_BUFFER_SIZE];
int n;
while( (n = in.read(buf)) >= 0 ) {
out.write( buf, 0, n );
}
Run Code Online (Sandbox Code Playgroud)
(ina Reader和outa 在哪里Writer)?
eri*_*son 17
不,CharBuffer在这种情况下,没有理由更喜欢.
但是,一般而言,CharBuffer(和ByteBuffer)可以真正简化API并鼓励正确处理.如果您正在设计公共API,那么绝对值得考虑面向缓冲区的API.
我想对这种比较进行微型基准测试.
以下是我写的课程.
事情是我无法相信CharBuffer表现如此糟糕.我有什么问题?
编辑:由于下面的第11条评论我已经编辑了代码和输出时间,所以在各方面都有更好的表现,但在时间上仍然存在显着差异.我还尝试了注释中提到的out2.append((CharBuffer)buff.flip())选项,但它比下面代码中使用的write选项慢得多.
结果:(以ms为单位)
char []:3411
CharBuffer:5653
public class CharBufferScratchBox
{
public static void main(String[] args) throws Exception
{
// Some Setup Stuff
String smallString =
"1111111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
stringBuilder.append(smallString);
}
String string = stringBuilder.toString();
int DEFAULT_BUFFER_SIZE = 1000;
int ITTERATIONS = 10000;
// char[]
StringReader in1 = null;
StringWriter out1 = null;
Date start = new Date();
for (int i = 0; i < ITTERATIONS; i++)
{
in1 = new StringReader(string);
out1 = new StringWriter(string.length());
char[] buf = new char[DEFAULT_BUFFER_SIZE];
int n;
while ((n = in1.read(buf)) >= 0)
{
out1.write(
buf,
0,
n);
}
}
Date done = new Date();
System.out.println("char[] : " + (done.getTime() - start.getTime()));
// CharBuffer
StringReader in2 = null;
StringWriter out2 = null;
start = new Date();
CharBuffer buff = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
for (int i = 0; i < ITTERATIONS; i++)
{
in2 = new StringReader(string);
out2 = new StringWriter(string.length());
int n;
while ((n = in2.read(buff)) >= 0)
{
out2.write(
buff.array(),
0,
n);
buff.clear();
}
}
done = new Date();
System.out.println("CharBuffer: " + (done.getTime() - start.getTime()));
}
}
Run Code Online (Sandbox Code Playgroud)