Performance on local constants?
John Machin
sjmachin at lexicon.net
Sun Dec 23 01:55:07 EST 2007
On Dec 23, 2:39 pm, "Terry Reedy" <tjre... at udel.edu> wrote:
> "John Machin" <sjmac... at lexicon.net> wrote in message
>
> news:ab88db50-ce4e-4298-bcec-079de67dbcb8 at e25g2000prg.googlegroups.com...
> | On Dec 23, 5:38 am, "Terry Reedy" <tjre... at udel.edu> wrote:
> | > 'Most flexible' in a different way is
> | >
> | > def searcher(rex):
> | > crex = re.compile(rex)
> | > def _(txt):
> | > return crex.search(txt)
> | > return _
> | >
> |
> | I see your obfuscatory ante and raise you several dots and
> | underscores:
>
> I will presume you are merely joking, but for the benefit of any beginning
> programmers reading this, the closure above is a standard functional idiom
> for partial evaluation of a function (in this this, re.search(crex,txt))
>
> | class Searcher(object):
> | def __init__(self, rex):
> | self.crex = re.compile(rex)
> | def __call__(self, txt):
> | return self.crex.search(txt)
>
> while this is, the equivalent OO version. Intermdiate Python programmers
> should know both.
>
Semi-joking; I thought that your offering of this:
def searcher(rex):
crex = re.compile(rex)
def _(txt):
return crex.search(txt)
return _
foo_searcher = searcher('foo')
was somewhat over-complicated, and possibly slower than already-
mentioned alternatives. The standard idiom etc etc it may be, but the
OP was interested in getting overhead out of his re searching loop.
Let's trim it a bit.
step 1:
def searcher(rex):
crexs = re.compile(rex).search
def _(txt):
return crexs(txt)
return _
foo_searcher = searcher('foo')
step 2:
def searcher(rex):
return re.compile(rex).search
foo_searcher = searcher('foo')
step 3:
foo_searcher = re.compile('foo').search
HTH,
John
More information about the Python-list
mailing list