Ticket #11778: test_escapejs.py

File test_escapejs.py, 1.8 KB (added by josephdrose, 15 years ago)
Line 
1import re, time
2
3test_string="Hello, I'm a simple string we're going to use. \\ - ; &"
4iterations=50000
5
6###################old implementation##################
7_base_js_escapes = (
8 ('\\', r'\x5C'),
9 ('\'', r'\x27'),
10 ('"', r'\x22'),
11 ('>', r'\x3E'),
12 ('<', r'\x3C'),
13 ('&', r'\x26'),
14 ('=', r'\x3D'),
15 ('-', r'\x2D'),
16 (';', r'\x3B')
17)
18
19# Escape every ASCII character with a value less than 32.
20_js_escapes = (_base_js_escapes +
21 tuple([('%c' % z, '\\x%02X' % z) for z in range(32)]))
22
23def escapejs(value):
24 for bad, good in _js_escapes:
25 value = value.replace(bad, good)
26 return value
27#######################################################
28
29#time old implementation
30t1=time.time()
31for x in range(iterations):
32 escapejs(test_string)
33t2=time.time()
34print 'old implementation took %0.3f ms' % ((t2-t1)*1000.0)
35print 'value calculated: %s' % escapejs(test_string)
36
37#####################new implementation################
38_base_js_escapes = (
39 ('\\', r'\x5C'),
40 ('\'', r'\x27'),
41 ('"', r'\x22'),
42 ('>', r'\x3E'),
43 ('<', r'\x3C'),
44 ('&', r'\x26'),
45 ('=', r'\x3D'),
46 ('-', r'\x2D'),
47 (';', r'\x3B')
48)
49
50# Escape every ASCII character with a value less than 32.
51_js_escapes = (_base_js_escapes +
52 tuple([('%c' % z, '\\x%02X' % z) for z in range(32)]))
53
54_js_escapes_dict={}
55for k, v in _js_escapes:
56 _js_escapes_dict[k]=v
57
58_js_escapes_re = re.compile(u'[\u0000-\u001f]|\\\\|\'|"|>|<|&|=|-|;')
59
60def escapejs_new(value):
61 return _js_escapes_re.sub(lambda m: _js_escapes_dict[m.group(0)], value)
62#######################################################
63
64
65#time new implementation
66t1=time.time()
67for x in range(iterations):
68 escapejs_new(test_string)
69t2=time.time()
70print 'new implementation took %0.3f ms' % ((t2-t1)*1000.0)
71print 'value calculated: %s' % escapejs_new(test_string)
Back to Top