Skip to content

Commit 4d30756

Browse files
authored
gh-150820: Speed up json.dumps() for small documents (GH-150827)
Only create the float formatting helper when the pure Python encoder is used.
1 parent 76d556e commit 4d30756

2 files changed

Lines changed: 23 additions & 23 deletions

File tree

Lib/json/encoder.py

Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -223,29 +223,6 @@ def iterencode(self, o, _one_shot=False):
223223
else:
224224
_encoder = encode_basestring
225225

226-
def floatstr(o, allow_nan=self.allow_nan,
227-
_repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
228-
# Check for specials. Note that this type of test is processor
229-
# and/or platform-specific, so do tests which don't depend on the
230-
# internals.
231-
232-
if o != o:
233-
text = 'NaN'
234-
elif o == _inf:
235-
text = 'Infinity'
236-
elif o == _neginf:
237-
text = '-Infinity'
238-
else:
239-
return _repr(o)
240-
241-
if not allow_nan:
242-
raise ValueError(
243-
"Out of range float values are not JSON compliant: " +
244-
repr(o))
245-
246-
return text
247-
248-
249226
if self.indent is None or isinstance(self.indent, str):
250227
indent = self.indent
251228
else:
@@ -256,6 +233,28 @@ def floatstr(o, allow_nan=self.allow_nan,
256233
self.key_separator, self.item_separator, self.sort_keys,
257234
self.skipkeys, self.allow_nan)
258235
else:
236+
def floatstr(o, allow_nan=self.allow_nan,
237+
_repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
238+
# Check for specials. Note that this type of test is processor
239+
# and/or platform-specific, so do tests which don't depend on
240+
# the internals.
241+
242+
if o != o:
243+
text = 'NaN'
244+
elif o == _inf:
245+
text = 'Infinity'
246+
elif o == _neginf:
247+
text = '-Infinity'
248+
else:
249+
return _repr(o)
250+
251+
if not allow_nan:
252+
raise ValueError(
253+
"Out of range float values are not JSON compliant: " +
254+
repr(o))
255+
256+
return text
257+
259258
_iterencode = _make_iterencode(
260259
markers, self.default, _encoder, indent, floatstr,
261260
self.key_separator, self.item_separator, self.sort_keys,
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Speed up :func:`json.dumps` for small documents. Patch by Bernát Gábor.

0 commit comments

Comments
 (0)