From f0f1698e465667d2180c451b0b7d5c30d7bd1491 Mon Sep 17 00:00:00 2001 From: Emmanuel Gil Peyrot Date: Wed, 17 Aug 2016 00:39:27 +0100 Subject: [PATCH] ElementBase: micro-optimise __getitem__, hands down the most often called function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes it go down from 8.767s to 7.960s in a random benchmark. Remove unnecessary assignations, don’t create an OrderedDict from a dict to then convert it to a dict again, only obtain the get_method2 name if get_method wasn’t present. get_method2 (the title-case one) takes about 1/8th of the total time spent in this function, we should eliminate it as soon as possible. --- slixmpp/xmlstream/stanzabase.py | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/slixmpp/xmlstream/stanzabase.py b/slixmpp/xmlstream/stanzabase.py index 1ddee825..c1f297ac 100644 --- a/slixmpp/xmlstream/stanzabase.py +++ b/slixmpp/xmlstream/stanzabase.py @@ -637,7 +637,7 @@ class ElementBase(object): plugin.values = value return self - def __getitem__(self, attrib): + def __getitem__(self, full_attrib): """Return the value of a stanza interface using dict-like syntax. Example:: @@ -664,24 +664,16 @@ class ElementBase(object): 8. The plugin named ``'foo'`` 9. An empty string. - :param string attrib: The name of the requested stanza interface. + :param string full_attrib: The name of the requested stanza interface. """ - full_attrib = attrib - attrib_lang = ('%s|' % attrib).split('|') - attrib = attrib_lang[0] - lang = attrib_lang[1] or None + attrib, lang, *_ = ('%s|' % full_attrib).split('|') - kwargs = {} - if lang and attrib in self.lang_interfaces: - kwargs['lang'] = lang - - kwargs = OrderedDict(kwargs) + kwargs = {'lang': lang} if lang and attrib in self.lang_interfaces else {} if attrib == 'substanzas': return self.iterables elif attrib in self.interfaces or attrib == 'lang': get_method = "get_%s" % attrib.lower() - get_method2 = "get%s" % attrib.title() if self.plugin_overrides: name = self.plugin_overrides.get(get_method, None) @@ -694,7 +686,8 @@ class ElementBase(object): if hasattr(self, get_method): return getattr(self, get_method)(**kwargs) - elif hasattr(self, get_method2): + get_method2 = "get%s" % attrib.title() + if hasattr(self, get_method2): return getattr(self, get_method2)(**kwargs) else: if attrib in self.sub_interfaces: