Skip to content

Commit de2340c

Browse files
committed
perf: Reduce per-entry Python overhead in add_entry
Signed-off-by: Dmitry Dygalo <dmitry@dygalo.dev>
1 parent 76800e2 commit de2340c

1 file changed

Lines changed: 19 additions & 13 deletions

File tree

src/harfile/__init__.py

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@
4545

4646
HAR_VERSION = "1.2"
4747

48+
# A single reusable encoder avoids the per-call argument handling in ``json.dumps``.
49+
# With default options this produces output identical to ``json.dumps(obj)``.
50+
_encode = json.JSONEncoder().encode
51+
4852

4953
class HarFile:
5054
_fd: IO[str]
@@ -140,25 +144,27 @@ def add_entry(
140144
self._has_preable = True
141145
separator = "\n" if self._is_first_entry else ",\n"
142146
self._is_first_entry = False
143-
write = self._fd.write
144-
dumps = json.dumps
147+
dumps = _encode
145148
if isinstance(startedDateTime, datetime):
146149
startedDateTime = startedDateTime.isoformat()
147-
write(f"{separator} {{")
148-
write(f'\n "startedDateTime": "{startedDateTime}",')
149-
write(f'\n "time": {time},')
150-
write(f'\n "request": {dumps(request.asdict())},')
151-
write(f'\n "response": {dumps(response.asdict())},')
152-
write(f'\n "timings": {dumps(timings.asdict())},')
153150
cache = cache or Cache()
154-
write(f'\n "cache": {dumps(cache.asdict())}')
151+
chunk = (
152+
f"{separator} {{"
153+
f'\n "startedDateTime": "{startedDateTime}",'
154+
f'\n "time": {time},'
155+
f'\n "request": {dumps(request.asdict())},'
156+
f'\n "response": {dumps(response.asdict())},'
157+
f'\n "timings": {dumps(timings.asdict())},'
158+
f'\n "cache": {dumps(cache.asdict())}'
159+
)
155160
if serverIPAddress:
156-
write(f',\n "serverIPAddress": {dumps(serverIPAddress)}')
161+
chunk += f',\n "serverIPAddress": {dumps(serverIPAddress)}'
157162
if connection:
158-
write(f',\n "connection": {dumps(connection)}')
163+
chunk += f',\n "connection": {dumps(connection)}'
159164
if comment:
160-
write(f',\n "comment": {dumps(comment)}')
161-
write("\n }")
165+
chunk += f',\n "comment": {dumps(comment)}'
166+
chunk += "\n }"
167+
self._fd.write(chunk)
162168

163169
def _write_preamble(self) -> None:
164170
creator = f"""{{

0 commit comments

Comments
 (0)