ChannelBufferInputStream responseStream = (ChannelBufferInputStream) response.getBodyAsStream();
ArrayList<Byte> arrayList = new ArrayList<Byte>();
try {
while (responseStream.available() > 0) {
arrayList.add(responseStream.readByte());
}
} catch (IOException e) {
e.printStackTrace();
return internalServerError();
}
Iterator<Byte> iterator = arrayList.iterator();
byte[] bytes = new byte[arrayList.size()];
int i = 0;
while (iterator.hasNext()) {
bytes[i++] = iterator.next();
}
在我的网络应用程序的每个页面加载时都会调用此代码。它似乎运行得很快,但是有什么可以使它运行得更快吗?
编辑 - 使用字节数组输出流更新
ChannelBufferInputStream responseStream = (ChannelBufferInputStream) response.getBodyAsStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
int read = responseStream.read();
while (read != -1) {
byteArrayOutputStream.write(read);
read = responseStream.read();
}
} catch (IOException e) {
e.printStackTrace();
return internalServerError();
}
byte[] bytes = byteArrayOutputStream.toByteArray();
return ok(bytes).as(response.getHeader("Content-type"));
编辑 - 基准测试代码
ChannelBufferInputStream responseStream = (ChannelBufferInputStream) response.getBodyAsStream();
long t1 = System.nanoTime();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
int read = responseStream.read();
while (read != -1) {
byteArrayOutputStream.write(read);
read = responseStream.read();
}
} catch (IOException e) {
e.printStackTrace();
return internalServerError();
}
byte[] bytes = byteArrayOutputStream.toByteArray();
long t2 = System.nanoTime();
System.out.println(t2-t1);
return ok(bytes).as(response.getHeader("Content-type"));
100+ 次请求后的平均时间 - 46873
ChannelBufferInputStream responseStream = (ChannelBufferInputStream) response.getBodyAsStream();
long t1 = System.nanoTime();
ArrayList<Byte> arrayList = new ArrayList<Byte>();
try {
while (responseStream.available() > 0) {
arrayList.add(responseStream.readByte());
}
} catch (IOException e) {
e.printStackTrace();
return internalServerError();
}
Iterator<Byte> iterator = arrayList.iterator();
byte[] bytes = new byte[arrayList.size()];
int i = 0;
while (iterator.hasNext()) {
bytes[i++] = iterator.next();
}
long t2 = System.nanoTime();
System.out.println(t2-t1);
return ok(bytes).as(response.getHeader("Content-type"));
100+ 次请求后的平均时间 - 522848
long t1 = System.nanoTime();
byte[] bytes;
try {
bytes = org.apache.commons.io.IOUtils.toByteArray(responseStream);
} catch (Exception e) {
return internalServerError();
}
long t2 = System.nanoTime();
System.out.println(t2-t1);
100+ 次请求后的平均时间 - 45088
long t1 = System.nanoTime();
byte[] bytes;
try {
bytes = sun.misc.IOUtils.readFully(responseStream, -1, true);
} catch (Exception e) {
return internalServerError();
}
long t2 = System.nanoTime();
System.out.println(t2 - t1);
100+ 次请求后的平均时间 - 20180