Ticket #11778: escapejs_benchmark.py

File escapejs_benchmark.py, 2.2 KB (added by gisle, 15 years ago)

Updated benchmark script

Line 
1import re, time
2
3###################old implementation##################
4_base_js_escapes = (
5 ('\\', r'\x5C'),
6 ('\'', r'\x27'),
7 ('"', r'\x22'),
8 ('>', r'\x3E'),
9 ('<', r'\x3C'),
10 ('&', r'\x26'),
11 ('=', r'\x3D'),
12 ('-', r'\x2D'),
13 (';', r'\x3B')
14)
15
16# Escape every ASCII character with a value less than 32.
17_js_escapes = (_base_js_escapes +
18 tuple([('%c' % z, '\\x%02X' % z) for z in range(32)]))
19
20def escapejs(value):
21 for bad, good in _js_escapes:
22 value = value.replace(bad, good)
23 return value
24#######################################################
25
26#####################new implementation################
27_js_escapes_dict = {
28 '\\': r'\x5C',
29 '\'': r'\x27',
30 '"': r'\x22',
31 '>': r'\x3E',
32 '<': r'\x3C',
33 '&': r'\x26',
34 '=': r'\x3D',
35 '-': r'\x2D',
36 ';': r'\x3B',
37 u'\u2028': r'\u2028',
38 u'\u2029': r'\u2029',
39}
40
41# also escape every ASCII character with a value less than 32.
42for z in range(32):
43 _js_escapes_dict[chr(z)] = '\\x%02X' % z
44
45# construct a Regex object matching the keys in _js_escapes_dict
46_js_escapes_re = u''.join(sorted(_js_escapes_dict.keys()))
47_js_escapes_re = re.sub(r'[\\\\\-\]]', r'\\\g<0>', _js_escapes_re) # escape \-]
48_js_escapes_re = '[' + _js_escapes_re + ']'
49_js_escapes_re = re.compile(_js_escapes_re)
50
51def escapejs_new(value):
52 """Hex encodes characters for use in JavaScript strings."""
53 return _js_escapes_re.sub(lambda m: _js_escapes_dict[m.group(0)], value)
54#######################################################
55
56# time the functions
57n = 100000
58for test_string in (
59 "x" * 5, "x" * 512, "'" * 5, "'" * 512,
60 "Hello, I'm a simple string we're going to use. \\ - ; &",
61):
62
63 t_old = time.time()
64 for x in range(n):
65 escapejs(test_string)
66 t_old = time.time() - t_old
67
68 t_new = time.time()
69 for x in range(n):
70 escapejs_new(test_string)
71 t_new = time.time() - t_new
72
73 str = test_string
74 if len(str) > 10:
75 str = str[:10] + "..."
76 if t_new < t_old:
77 print "%5.1fx speedup %.1fs vs %.1fs %r" % (t_old / t_new, t_old, t_new, str)
78 else:
79 print "%5.1fx slowdown %.1fs vs %.1fs %r" % (t_new / t_old, t_old, t_new, str)
80
Back to Top