aboutsummaryrefslogtreecommitdiffstats
path: root/microbenchmark-template/src/test/java/org/sonar/microbenchmark/SerializationBenchmarkTest.java
blob: 11fd98223eb44583f0b5a3aeb4e7e94211d686c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package org.sonar.microbenchmark;

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.Deflater;

public class SerializationBenchmarkTest {

  SerializationBenchmark benchmark = new SerializationBenchmark();

  @Before
  public void setUp() throws Exception {
    benchmark.setup();
  }

  @Test
  public void size_of_gson_output() throws Exception {
    benchmark.write_gson();
    System.out.println("GSON: " + sizeOf(benchmark.outputFile));
    System.out.println("GSON (zipped): " + sizeOf(zipFile(benchmark.outputFile)));
  }

  @Test
  public void size_of_protobuf_output() throws Exception {
    benchmark.write_protobuf();
    System.out.println("Protocol Buffers: " + sizeOf(benchmark.outputFile));
    System.out.println("Protocol Buffers (zipped): " + sizeOf(zipFile(benchmark.outputFile)));
  }

  @Test
  public void size_of_serializable_output() throws Exception {
    benchmark.write_serializable();
    System.out.println("java.io.Serializable: " + sizeOf(benchmark.outputFile));
    System.out.println("java.io.Serializable (zipped): " + sizeOf(zipFile(benchmark.outputFile)));
  }

  @Test
  public void size_of_externalizable_output() throws Exception {
    benchmark.write_externalizable();
    System.out.println("java.io.Externalizable: " + sizeOf(benchmark.outputFile));
    System.out.println("java.io.Externalizable (zipped): " + sizeOf(zipFile(benchmark.outputFile)));
  }

  @Test
  public void size_of_kryo_output() throws Exception {
    benchmark.write_kryo();
    System.out.println("Kryo: " + sizeOf(benchmark.outputFile));
    System.out.println("Kryo (zipped): " + sizeOf(zipFile(benchmark.outputFile)));
  }

  private String sizeOf(File file) {
    return FileUtils.byteCountToDisplaySize(FileUtils.sizeOf(file));
  }

  private File zipFile(File input) throws Exception {
    File zipFile = new File(input.getAbsolutePath() + ".zip");
    Deflater deflater = new Deflater();
    byte[] content = FileUtils.readFileToByteArray(input);
    deflater.setInput(content);
    OutputStream outputStream = new FileOutputStream(zipFile);
    deflater.finish();
    byte[] buffer = new byte[1024];
    while (!deflater.finished()) {
      int count = deflater.deflate(buffer); // returns the generated code... index
      outputStream.write(buffer, 0, count);
    }
    outputStream.close();
    deflater.end();

    return zipFile;
  }
}