Skip to content

Commit 50c3afb

Browse files
author
Douglas Crockford
committed
keyPool
1 parent 1b5a59f commit 50c3afb

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

JSONObject.java

+23-1
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,21 @@ of this software and associated documentation files (the "Software"), to deal
9191
* </ul>
9292
*
9393
* @author JSON.org
94-
* @version 2012-10-27
94+
* @version 2012-12-01
9595
*/
9696
public class JSONObject {
97+
/**
98+
* The maximum number of keys in the key pool.
99+
*/
100+
private static final int keyPoolSize = 100;
101+
102+
/**
103+
* Key pooling is like string interning, but without permanently tying up
104+
* memory. To help conserve memory, storage of duplicated key strings in
105+
* JSONObjects will be avoided by using a key pool to manage unique key
106+
* string objects. This is used by JSONObject.put(string, object).
107+
*/
108+
private static HashMap keyPool = new HashMap(keyPoolSize);
97109

98110
/**
99111
* JSONObject.NULL is equivalent to the value that JavaScript calls null,
@@ -1110,11 +1122,21 @@ public JSONObject put(String key, Map value) throws JSONException {
11101122
* or if the key is null.
11111123
*/
11121124
public JSONObject put(String key, Object value) throws JSONException {
1125+
String pooled;
11131126
if (key == null) {
11141127
throw new JSONException("Null key.");
11151128
}
11161129
if (value != null) {
11171130
testValidity(value);
1131+
pooled = (String)keyPool.get(key);
1132+
if (pooled == null) {
1133+
if (keyPool.size() >= keyPoolSize) {
1134+
keyPool = new HashMap(keyPoolSize);
1135+
}
1136+
keyPool.put(key, key);
1137+
} else {
1138+
key = pooled;
1139+
}
11181140
this.map.put(key, value);
11191141
} else {
11201142
this.remove(key);

0 commit comments

Comments
 (0)