Can I do this faster?

Kevin Digweed Kevin.Digweed at dial.pipex.com
Wed Aug 9 04:15:06 EDT 2000


Hi Horst!

If you really want to speed this up, then your best bet is to keep the
data shadowed in a structure for which the row is the key (assuming it's
an immutable value).

For example (uncompiled and untested, but double-checked):

class foo: # (This is the class of 's', in your example)
    def generate_quick_lookup(self):
        self.quick = {}
        for key, value in self.__rowDict.items():
            self.quick[value['data']] = key

def __GetRowID(s, row):
    try:
        return s.quick[row]
    except KeyError:
        pass # Drop thru to return None.

Of course, it defeats the object if you need to call
s.generate_quick_lookup() each time before you call __GetRowID(), so
this approach only helps if you can keep the 'quick' dict up-to-date as
the row information upon which it's based is changed without having to
process the whole thing each time. And even then, the actual benefit
will depend on the ratio of lookups to modifications (I'm assuming that
the ratio is high in this case - and therefore it's a reasonable thing
to attempt - as you say the lookup code in question 'is executed very
often').

If you know that the 'row' values are all numeric, know the maximum row
value and know it's not too large to preclude having a list of that size
lying around, I suspect the following will be even faster doing the
actual lookup (same disclaimer re: testing as above):

class foo: # (This is the class of 's', in your example)
    def generate_quick_lookup(self):
        self.quick = [None] * MAX_ROW
        for key, value in self.__rowDict.items():
            self.quick[value['data']] = key

def __GetRowID(s, row):
    return s.quick[row] # Might want to try/except, but that would hide
out-of-range row errors.

Horst Gassner wrote:
> 
> Hello!
> 
> The following code is executed very often in my program and I would be
> happy if someone could help me to speed this up.
> 
> def __GetRowID (s, row):
>         for key in s.__rowDict.keys():
>                 if s.__rowDict[key]['data'] == row:
>                         return key
> 
> Thanx in advance
> Horst



More information about the Python-list mailing list