Skip to content

Commit 8678e50

Browse files
author
Minh Pham
committed
Use binary search to find field in CompatibleFieldSerializer for object with lots of fields
1 parent 1bb2641 commit 8678e50

File tree

1 file changed

+47
-10
lines changed

1 file changed

+47
-10
lines changed

src/com/esotericsoftware/kryo/serializers/CompatibleFieldSerializer.java

Lines changed: 47 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919

2020
package com.esotericsoftware.kryo.serializers;
2121

22-
import static com.esotericsoftware.minlog.Log.*;
22+
import static com.esotericsoftware.minlog.Log.TRACE;
23+
import static com.esotericsoftware.minlog.Log.trace;
2324

2425
import com.esotericsoftware.kryo.Kryo;
2526
import com.esotericsoftware.kryo.io.Input;
@@ -42,6 +43,9 @@
4243
* must be avoided.
4344
* @author Nathan Sweet <[email protected]> */
4445
public class CompatibleFieldSerializer<T> extends FieldSerializer<T> {
46+
/* For object with more than BINARY_SEARCH_THRESHOLD fields, use binary search instead of iterative search */
47+
private static final int THRESHOLD_BINARY_SEARCH = 32;
48+
4549
public CompatibleFieldSerializer (Kryo kryo, Class type) {
4650
super(kryo, type);
4751
}
@@ -78,17 +82,50 @@ public T read (Kryo kryo, Input input, Class<T> type) {
7882

7983
fields = new CachedField[length];
8084
CachedField[] allFields = getFields();
81-
outer:
82-
for (int i = 0, n = names.length; i < n; i++) {
83-
String schemaName = names[i];
84-
for (int ii = 0, nn = allFields.length; ii < nn; ii++) {
85-
if (allFields[ii].field.getName().equals(schemaName)) {
86-
fields[i] = allFields[ii];
87-
continue outer;
85+
86+
if (length < THRESHOLD_BINARY_SEARCH) {
87+
outer:
88+
for (int i = 0; i < length; i++) {
89+
String schemaName = names[i];
90+
for (int ii = 0, nn = allFields.length; ii < nn; ii++) {
91+
if (allFields[ii].field.getName().equals(schemaName)) {
92+
fields[i] = allFields[ii];
93+
continue outer;
94+
}
95+
}
96+
if (TRACE) trace("kryo", "Ignore obsolete field: " + schemaName);
97+
}
98+
} else {
99+
// binary search for schemaName
100+
int low, mid, high;
101+
int compare;
102+
outerBinarySearch:
103+
for (int i = 0; i < length; i++) {
104+
String schemaName = names[i];
105+
106+
low = 0;
107+
high = length - 1;
108+
109+
while (low <= high) {
110+
mid = (low + high) >>> 1;
111+
String midVal = allFields[mid].field.getName();
112+
compare = schemaName.compareTo(midVal);
113+
114+
if (compare < 0) {
115+
high = mid - 1;
116+
}
117+
else if (compare > 0) {
118+
low = mid + 1;
119+
}
120+
else {
121+
fields[i] = allFields[mid];
122+
continue outerBinarySearch;
123+
}
124+
}
125+
if (TRACE) trace("kryo", "Ignore obsolete field: " + schemaName);
88126
}
89-
}
90-
if (TRACE) trace("kryo", "Ignore obsolete field: " + schemaName);
91127
}
128+
92129
context.put(this, fields);
93130
}
94131

0 commit comments

Comments
 (0)