| 1 | import re, time
|
|---|
| 2 |
|
|---|
| 3 | test_string="Hello, I'm a simple string we're going to use. \\ - ; &"
|
|---|
| 4 | iterations=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 |
|
|---|
| 23 | def escapejs(value):
|
|---|
| 24 | for bad, good in _js_escapes:
|
|---|
| 25 | value = value.replace(bad, good)
|
|---|
| 26 | return value
|
|---|
| 27 | #######################################################
|
|---|
| 28 |
|
|---|
| 29 | #time old implementation
|
|---|
| 30 | t1=time.time()
|
|---|
| 31 | for x in range(iterations):
|
|---|
| 32 | escapejs(test_string)
|
|---|
| 33 | t2=time.time()
|
|---|
| 34 | print 'old implementation took %0.3f ms' % ((t2-t1)*1000.0)
|
|---|
| 35 | print '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={}
|
|---|
| 55 | for k, v in _js_escapes:
|
|---|
| 56 | _js_escapes_dict[k]=v
|
|---|
| 57 |
|
|---|
| 58 | _js_escapes_re = re.compile(u'[\u0000-\u001f]|\\\\|\'|"|>|<|&|=|-|;')
|
|---|
| 59 |
|
|---|
| 60 | def 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
|
|---|
| 66 | t1=time.time()
|
|---|
| 67 | for x in range(iterations):
|
|---|
| 68 | escapejs_new(test_string)
|
|---|
| 69 | t2=time.time()
|
|---|
| 70 | print 'new implementation took %0.3f ms' % ((t2-t1)*1000.0)
|
|---|
| 71 | print 'value calculated: %s' % escapejs_new(test_string)
|
|---|