1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.forgerock.http.serialization;
18
19 import static org.forgerock.json.JsonValue.array;
20 import static org.forgerock.json.JsonValue.field;
21 import static org.forgerock.json.JsonValue.json;
22 import static org.forgerock.json.JsonValue.object;
23
24 import java.io.IOException;
25 import java.util.concurrent.TimeUnit;
26
27 import org.forgerock.http.util.Json;
28 import org.forgerock.json.JsonValue;
29 import org.forgerock.util.i18n.LocalizableString;
30 import org.forgerock.util.i18n.PreferredLocales;
31 import org.openjdk.jmh.annotations.Benchmark;
32 import org.openjdk.jmh.annotations.BenchmarkMode;
33 import org.openjdk.jmh.annotations.Fork;
34 import org.openjdk.jmh.annotations.Measurement;
35 import org.openjdk.jmh.annotations.Mode;
36 import org.openjdk.jmh.annotations.OutputTimeUnit;
37 import org.openjdk.jmh.annotations.Scope;
38 import org.openjdk.jmh.annotations.State;
39 import org.openjdk.jmh.annotations.Warmup;
40 import org.openjdk.jmh.runner.Runner;
41 import org.openjdk.jmh.runner.RunnerException;
42 import org.openjdk.jmh.runner.options.Options;
43 import org.openjdk.jmh.runner.options.OptionsBuilder;
44
45 import com.fasterxml.jackson.databind.ObjectMapper;
46
47 @State(Scope.Thread)
48 @BenchmarkMode(Mode.AverageTime)
49 @OutputTimeUnit(TimeUnit.NANOSECONDS)
50 @Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
51 @Measurement(iterations = 1, time = 10, timeUnit = TimeUnit.SECONDS)
52 public class JacksonJsonSerialization {
53
54 private static final JsonValue TARGET = json(object(
55 field("string", "a string"),
56 field("number", 145.644D),
57 field("bool", true),
58 field("obj", object(
59 field("localizable", new LocalizableString("not localizable"))
60 )),
61 field("array", json(array(
62 "1",
63 "2",
64 "3"
65 )))
66 ));
67
68 private static final PreferredLocales LOCALES = new PreferredLocales();
69
70 private static final ObjectMapper MAPPER = new ObjectMapper()
71 .registerModules(new Json.JsonValueModule(), new Json.LocalizableStringModule());
72
73 @Benchmark
74 public byte[] testDefaultJson() throws IOException {
75 return Json.writeJson(TARGET);
76 }
77
78 @Benchmark
79 public byte[] testConstructObjectMapperEachTime() throws IOException {
80 return new ObjectMapper()
81 .registerModules(new Json.JsonValueModule(), new Json.LocalizableStringModule())
82 .writeValueAsBytes(TARGET);
83 }
84
85 @Benchmark
86 public byte[] testWithAttribute() throws IOException {
87 return Json.makeLocalizingObjectWriter(MAPPER, LOCALES).writeValueAsBytes(TARGET);
88 }
89
90 public static void main(String[] args) throws RunnerException {
91 Options opt = new OptionsBuilder()
92 .include(JacksonJsonSerialization.class.getSimpleName())
93 .build();
94
95 new Runner(opt).run();
96 }
97
98 }