Created
August 12, 2021 17:27
-
-
Save clokep/17064b16a9b471d09feb3e61851886af to your computer and use it in GitHub Desktop.
JSON Schema benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pyperf | |
import time | |
import jsonschema | |
from jsonschema.exceptions import best_match | |
SCHEMA = { | |
"type": "object", | |
"properties": { | |
"displayname": {"oneOf": [{"type": "string"}, {"type": "null"}]}, | |
}, | |
"required": ["displayname"], | |
} | |
VALIDATOR = jsonschema.Draft7Validator(SCHEMA) | |
def json_schema(content): | |
try: | |
VALIDATOR.validate(content) | |
except jsonschema.ValidationError: | |
pass | |
else: | |
return content["displayname"] | |
def manual(content): | |
try: | |
displayname = content["displayname"] | |
except KeyError: | |
pass | |
else: | |
if isinstance(displayname, str): | |
return content["displayname"] | |
runner = pyperf.Runner() | |
for name, content in (("empty", {}), ("wrong_type", {"displayname": 1}), ("good", {"displayname": "Bob"})): | |
runner.bench_func('json_schema_%s' % name, json_schema, content) | |
runner.bench_func('manual_%s' % name, manual, {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See matrix-org/synapse#8445 (comment)