Skip to content

Commit 774e0b7

Browse files
author
leelovejava
committed
add 压缩20M文件从30秒到1秒的优化过程
1 parent 42b4625 commit 774e0b7

File tree

1 file changed

+13
-12
lines changed
  • java-new-features/jdk8-learning/src/test/java/com/leelovejava/zip

1 file changed

+13
-12
lines changed

java-new-features/jdk8-learning/src/test/java/com/leelovejava/zip/ZipTest.java

+13-12
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@ public class ZipTest {
2222
private static final String JPG_FILE_DIRECTORY = "D:\\logs\\test\\photo\\";
2323

2424
public static void main(String[] args) {
25-
zipFileNoBuffer();
25+
///zipFileNoBuffer();
2626
///zipFileBuffer();
27-
//zipFileChannel();
27+
///zipFileChannel();
2828
///zipFileMap();
29-
//zipFilePip();
29+
///zipFilePip();
3030
}
3131

3232
/**
@@ -42,6 +42,7 @@ public static void zipFileNoBuffer() {
4242
try (InputStream input = new FileInputStream(file)) {
4343
zipOut.putNextEntry(new ZipEntry(file.getName()));
4444
int temp;
45+
// 调用本地方法与原生操作系统进行交互,从磁盘中读取数据。每读取一个字节的数据就调用一次本地方法与操作系统交互,是非常耗时的
4546
while ((temp = input.read()) != -1) {
4647
zipOut.write(temp);
4748
}
@@ -68,6 +69,8 @@ public static void zipFileBuffer() {
6869
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) {
6970
zipOut.putNextEntry(new ZipEntry(file.getName()));
7071
int temp;
72+
// 如果使用缓冲区的话(这里假设初始的缓冲区大小足够放下30000字节的数据)那么只需要调用一次就行。
73+
// 因为缓冲区在第一次调用read()方法的时候会直接从磁盘中将数据直接读取到内存中。随后再一个字节一个字节的慢慢返回。
7174
while ((temp = bufferedInputStream.read()) != -1) {
7275
bufferedOutputStream.write(temp);
7376
}
@@ -103,8 +106,8 @@ public static void zipFileChannel() {
103106
}
104107

105108
/**
106-
* 使用内存映射文件
107-
* Version 4 使用Map映射文件
109+
* Version 4 使用Map内存映射文件
110+
* 内存中开辟了一段直接缓冲区,与数据直接作交互
108111
*/
109112
public static void zipFileMap() {
110113
// 开始时间
@@ -186,17 +189,15 @@ public static void runTask(Pipe pipe) {
186189
}
187190

188191
/**
189-
* noBuffer,
190-
* buffer,
191-
* channel,fileSize:859M,consume time:77366
192-
* map
193-
* pip
192+
* noBuffer,fileSize:20M,consume time:93916
193+
* buffer,fileSize:20M,consume time:4478
194+
* channel,fileSize:20M,consume time:2711
195+
* map,fileSize:20M,consume time:2395
196+
* pip,fileSize:20M,consume time:3312
194197
*
195198
* @param time 开始时间
196199
*/
197200
private static void printInfo(long time) {
198-
// fileSize:20M
199-
// consume time:29599
200201
long size = FileUtils.sizeOfDirectory(new File(JPG_FILE_DIRECTORY));
201202
System.out.println("fileSize:" + (size / 1024 / 1024) + "M");
202203
System.out.println("consume time:" + (System.currentTimeMillis() - time));

0 commit comments

Comments
 (0)