|
| 1 | +package com.jsoniter.demo; |
| 2 | + |
| 3 | +import com.jsoniter.Any; |
| 4 | +import com.jsoniter.JsonIterator; |
| 5 | +import com.jsoniter.Slice; |
| 6 | +import org.junit.Test; |
| 7 | +import org.openjdk.jmh.Main; |
| 8 | +import org.openjdk.jmh.annotations.*; |
| 9 | +import org.openjdk.jmh.infra.BenchmarkParams; |
| 10 | +import org.openjdk.jmh.infra.Blackhole; |
| 11 | + |
| 12 | +import java.io.IOException; |
| 13 | +import java.io.InputStream; |
| 14 | +import java.util.List; |
| 15 | +import java.util.Map; |
| 16 | + |
| 17 | +@State(Scope.Thread) |
| 18 | +public class LazyAny { |
| 19 | + |
| 20 | + private JsonIterator iter; |
| 21 | + private Slice input; |
| 22 | + |
| 23 | + @Setup(Level.Trial) |
| 24 | + public void benchSetup(BenchmarkParams params) throws IOException { |
| 25 | + InputStream resourceAsStream = LazyAny.class.getResourceAsStream("/large.json"); |
| 26 | + byte[] buf = new byte[32 * 1024]; |
| 27 | + int size = resourceAsStream.read(buf); |
| 28 | + input = new Slice(buf, 0, size); |
| 29 | + iter = new JsonIterator(); |
| 30 | + } |
| 31 | + |
| 32 | + public static void main(String[] args) throws Exception { |
| 33 | + Main.main(new String[]{ |
| 34 | + "LazyAny", |
| 35 | + "-i", "5", |
| 36 | + "-wi", "5", |
| 37 | + "-f", "1", |
| 38 | + "-prof", "stack", |
| 39 | + }); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + public void test() throws IOException { |
| 44 | + benchSetup(null); |
| 45 | + System.out.println(jsoniter()); |
| 46 | + System.out.println(jsoniter_object()); |
| 47 | + } |
| 48 | + |
| 49 | + @Benchmark |
| 50 | + public void jsoniter(Blackhole bh) throws IOException { |
| 51 | + bh.consume(jsoniter()); |
| 52 | + } |
| 53 | + |
| 54 | + @Benchmark |
| 55 | + public void jsoniter_object(Blackhole bh) throws IOException { |
| 56 | + bh.consume(jsoniter_object()); |
| 57 | + } |
| 58 | + |
| 59 | + public int jsoniter() throws IOException { |
| 60 | + iter.reset(input); |
| 61 | +Any users = iter.readAny(); |
| 62 | +int total = 0; |
| 63 | +for (Any user : users) { |
| 64 | + total += user.getValue("friends").size(); |
| 65 | +} |
| 66 | +return total; |
| 67 | + } |
| 68 | + |
| 69 | + public int jsoniter_object() throws IOException { |
| 70 | + iter.reset(input); |
| 71 | +List users = (List) iter.read(); |
| 72 | +int total = 0; |
| 73 | +for (Object userObj : users) { |
| 74 | + Map user = (Map) userObj; |
| 75 | + List friends = (List) user.get("friends"); |
| 76 | + total += friends.size(); |
| 77 | +} |
| 78 | +return total; |
| 79 | + } |
| 80 | +} |
0 commit comments