Patchwork [2,of,4,V2] encoding: initialize jsonmap when module is loaded

login
register
mail settings
Submitter Yuya Nishihara
Date Feb. 9, 2016, 3:40 p.m.
Message ID <13a9f3f8ffe0487e3ad2.1455032417@mimosa>
Download mbox | patch
Permalink /patch/13061/
State Accepted
Headers show

Comments

Yuya Nishihara - Feb. 9, 2016, 3:40 p.m.
# HG changeset patch
# User Yuya Nishihara <yuya@tcha.org>
# Date 1454150915 -32400
#      Sat Jan 30 19:48:35 2016 +0900
# Node ID 13a9f3f8ffe0487e3ad2b2bc31ff8e4cfa755d5c
# Parent  a5b995cfb26de1e1f90db90382e3332e227acf2e
encoding: initialize jsonmap when module is loaded

This makes jsonescape() a thread-safe function, which is necessary for hgweb.
The initialization stuff isn't that slow:

  $ python -m timeit -n1000 -s 'from mercurial import encoding as x' 'reload(x)'
  original:   1000 loops, best of 3: 158 usec per loop
  this patch: 1000 loops, best of 3: 214 usec per loop

compared to loading the commands module:

  $ python -m timeit -n1000 -s 'from mercurial import commands as x' 'reload(x)'
  1000 loops, best of 3: 1.11 msec per loop

Patch

diff --git a/mercurial/encoding.py b/mercurial/encoding.py
--- a/mercurial/encoding.py
+++ b/mercurial/encoding.py
@@ -379,6 +379,16 @@  class normcasespecs(object):
     other = 0
 
 _jsonmap = []
+_jsonmap.extend("\\u%04x" % x for x in xrange(32))
+_jsonmap.extend(chr(x) for x in xrange(32, 256))
+_jsonmap[0x7f] = '\\u007f'
+_jsonmap[0x09] = '\\t'
+_jsonmap[0x0a] = '\\n'
+_jsonmap[0x22] = '\\"'
+_jsonmap[0x5c] = '\\\\'
+_jsonmap[0x08] = '\\b'
+_jsonmap[0x0c] = '\\f'
+_jsonmap[0x0d] = '\\r'
 
 def jsonescape(s):
     '''returns a string suitable for JSON
@@ -407,18 +417,6 @@  def jsonescape(s):
     ''
     '''
 
-    if not _jsonmap:
-        _jsonmap.extend("\\u%04x" % x for x in xrange(32))
-        _jsonmap.extend(chr(x) for x in xrange(32, 256))
-        _jsonmap[0x7f] = '\\u007f'
-        _jsonmap[0x09] = '\\t'
-        _jsonmap[0x0a] = '\\n'
-        _jsonmap[0x22] = '\\"'
-        _jsonmap[0x5c] = '\\\\'
-        _jsonmap[0x08] = '\\b'
-        _jsonmap[0x0c] = '\\f'
-        _jsonmap[0x0d] = '\\r'
-
     return ''.join(_jsonmap[x] for x in bytearray(toutf8b(s)))
 
 _utf8len = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 4]