Skip to content

Commit 390aa22

Browse files
authored
Create java-howto.md
1 parent 590015e commit 390aa22

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

java-howto.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
---
2+
layout: default
3+
title: How-to
4+
---
5+
6+
# Simple Object binding
7+
8+
bind the json document
9+
10+
```json
11+
{"field1":100,"field2":101}
12+
```
13+
14+
to the class
15+
16+
```java
17+
public static class TestObject {
18+
public int field1;
19+
public int field2;
20+
}
21+
```
22+
23+
## iterator + switch case
24+
25+
```java
26+
TestObject obj = new TestObject();
27+
for (String field = iter.readObject(); field != null; field = iter.readObject()) {
28+
switch (field) {
29+
case "field1":
30+
obj.field1 = iter.readInt();
31+
continue;
32+
case "field2":
33+
obj.field2 = iter.readInt();
34+
continue;
35+
default:
36+
iter.skip();
37+
}
38+
}
39+
return obj;
40+
```
41+
42+
## iterator + if/else
43+
44+
```java
45+
TestObject obj = new TestObject();
46+
for (String field = iter.readObject(); field != null; field = iter.readObject()) {
47+
if (field.equals("field1")) {
48+
obj.field1 = iter.readInt();
49+
continue;
50+
}
51+
if (field.equals("field2")) {
52+
obj.field2 = iter.readInt();
53+
continue;
54+
}
55+
iter.skip();
56+
}
57+
return obj;
58+
```
59+
60+
## iterator + if/else + string.intern
61+
62+
```java
63+
TestObject obj = new TestObject();
64+
for (String field = iter.readObject(); field != null; field = iter.readObject()) {
65+
field = field.intern();
66+
if (field == "field1") {
67+
obj.field1 = iter.readInt();
68+
continue;
69+
}
70+
if (field == "field2") {
71+
obj.field2 = iter.readInt();
72+
continue;
73+
}
74+
iter.skip();
75+
}
76+
return obj;
77+
```
78+
79+
## performance
80+
81+
| style | ops/s |
82+
| --- | --- |
83+
| iterator + switch case | 10161124.096 ± 86811.453 ops/s |
84+
| iterator if/else | 10566399.972 ± 219004.245 ops/s |
85+
| iterator if/else + string.intern | 4091671.061 ± 59660.899 ops/s |
86+
87+
Do not use string.intern, it will not be faster. If/else might be slightly faster than switch/case, but swtich case is much more readable.

0 commit comments

Comments
 (0)