import json import regex from time import perf_counter jsonre_v1 = regex.compile( r''' (?: (?P \{\s* (?&members)? \s*\}) (?P (?&member) ( \s*,\s* (?&member) )*) (?P (?&string) \s*:\s* (?&value)) (?P \[\s* ((?&value) (\s*,\s* (?&value))*)? \s*\]) (?P " [^"\\]* (?: \\. | [^"\\]* )* ") (?P (?&integer) (?&fraction)? (?&exponent)?) (?P -? (?: 0 | [1-9][0-9]* )) (?P \. [0-9]*) (?P [eE] [-+]? [0-9]+) ){0} (?P (?&object) | (?&array) | (?&string) | (?&number) | true | false | null ) ''', flags=regex.VERBOSE|regex.UNICODE) jsonre_v2 = regex.compile( r''' (?P (?P \{\s* (?: (?P(?&string) \s*:\s* (?&value)) ( \s*,\s* (?&member) )* )? \s*\}) | (?P \[\s* ((?&value) (\s*,\s* (?&value))*)? \s*\]) | (?P " [^"\\]* (?: \\. | [^"\\]* )* ") | (?P (?P -? (?: 0 | [1-9][0-9]* )) (?: \. [0-9]* )? (?: [eE] [-+]? [0-9]+ )?) | true | false | null ) ''', flags=regex.VERBOSE|regex.UNICODE) s1 = json.dumps( {'key': [ {'bool': True, 'number': -0.00003}, {'string': 'hello world', 'unicode': '世界,你好'}]}) s2 = ('[' * 100) + (']' * 100) print('======= FIRST TEST =======') print(s1) print('jsonre_v1', 'matches' if jsonre_v1.match(s1) else 'does not match') t1 = perf_counter() for i in range(100): jsonre_v1.match(s1) t2 = perf_counter() print(f'jsonre_v1: 100x took {t2 - t1}s') print('jsonre_v2', 'matches' if jsonre_v2.match(s1) else 'does not match') t1 = perf_counter() for i in range(100): jsonre_v2.match(s1) t2 = perf_counter() print(f'jsonre_v2: 100x took {t2 - t1}s') t1 = perf_counter() for i in range(100): json.loads(s1) t2 = perf_counter() print(f'json module: 100x took {t2 - t1}s') print() print('======= SECOND TEST =======') print(s2) print('jsonre_v1', 'matches' if jsonre_v1.match(s2) else 'does not match') t1 = perf_counter() for i in range(100): jsonre_v1.match(s2) t2 = perf_counter() print(f'jsonre_v1: 100x took {t2 - t1}s') print('jsonre_v2', 'matches' if jsonre_v2.match(s2) else 'does not match') t1 = perf_counter() for i in range(100): jsonre_v2.match(s2) t2 = perf_counter() print(f'jsonre_v2: 100x took {t2 - t1}s') t1 = perf_counter() for i in range(100): json.loads(s2) t2 = perf_counter() print(f'json module: 100x took {t2 - t1}s') print() print('======= THIRD TEST =======') s3 = '{"key":' + s2 print(s3) print('jsonre_v1', 'matches' if jsonre_v1.match(s3) else 'does not match') t1 = perf_counter() for i in range(100): jsonre_v1.match(s3) t2 = perf_counter() print(f'jsonre_v1: 100x took {t2 - t1}s') print('jsonre_v2', 'matches' if jsonre_v2.match(s3) else 'does not match') t1 = perf_counter() for i in range(100): jsonre_v2.match(s3) t2 = perf_counter() print(f'jsonre_v2: 100x took {t2 - t1}s') t1 = perf_counter() for i in range(100): try: json.loads(s3) except json.JSONDecodeError: pass t2 = perf_counter() print(f'json module: 100x took {t2 - t1}s')