Skip to content

Instantly share code, notes, and snippets.

@clokep
Created August 12, 2021 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clokep/17064b16a9b471d09feb3e61851886af to your computer and use it in GitHub Desktop.
Save clokep/17064b16a9b471d09feb3e61851886af to your computer and use it in GitHub Desktop.
JSON Schema benchmark
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, {})
@clokep
Copy link
Author

clokep commented Nov 2, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment