Skip to content

Commit 029d2ab

Browse files
committed
reduce cost of NotFoundAny construction
1 parent 6925cf4 commit 029d2ab

2 files changed

Lines changed: 34 additions & 10 deletions

File tree

src/main/java/com/jsoniter/any/Any.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,8 @@ public int size() {
196196

197197
public Any mustBeValid() {
198198
if(this instanceof NotFoundAny) {
199-
throw ((NotFoundAny) this).exception;
199+
((NotFoundAny) this).throwException();
200+
return null;
200201
} else {
201202
return this;
202203
}

src/main/java/com/jsoniter/any/NotFoundAny.java

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,28 @@
1111

1212
class NotFoundAny extends Any {
1313

14-
protected final JsonException exception;
14+
private Object[] keys;
15+
private int idx;
16+
private Object obj, key;
17+
private final int exceptionMode;
1518

1619
public NotFoundAny(Object[] keys, int idx, Object obj) {
17-
this.exception = new JsonException(String.format("Value not found: failed to get path %s, because #%s section of the path ( %s ) not found in %s",
18-
Arrays.toString(keys), idx, keys[idx], obj));
20+
this.keys = keys;
21+
this.idx = idx;
22+
this.obj = obj;
23+
exceptionMode = 0;
1924
}
2025

2126
public NotFoundAny(int index, Object obj) {
22-
this.exception = new JsonException(String.format("Value not found: failed to get index %s from %s",
23-
index, obj));
27+
this.idx = index;
28+
this.obj = obj;
29+
exceptionMode = 1;
2430
}
2531

2632
public NotFoundAny(Object key, Object obj) {
27-
this.exception = new JsonException(String.format("Value not found: failed to get key %s from %s",
28-
key, obj));
33+
this.key = key;
34+
this.obj = obj;
35+
exceptionMode = 2;
2936
}
3037

3138
@Override
@@ -35,12 +42,28 @@ public ValueType valueType() {
3542

3643
@Override
3744
public Object object() {
38-
throw exception;
45+
throwException();
46+
return null;
47+
}
48+
49+
void throwException() {
50+
switch (exceptionMode) {
51+
case 0:
52+
throw new JsonException(String.format("Value not found: failed to get path %s, because #%s section of the path ( %s ) not found in %s",
53+
Arrays.toString(keys), idx, keys[idx], obj));
54+
case 1:
55+
throw new JsonException(String.format("Value not found: failed to get index %s from %s",
56+
idx, obj));
57+
case 2:
58+
throw new JsonException(String.format("Value not found: failed to get key %s from %s",
59+
key, obj));
60+
}
61+
throw new JsonException();
3962
}
4063

4164
@Override
4265
public void writeTo(JsonStream stream) throws IOException {
43-
throw exception;
66+
throwException();
4467
}
4568

4669
@Override

0 commit comments

Comments
 (0)