Can I do this faster?

Kevin Digweed Kevin.Digweed at dial.pipex.com
Wed Aug 9 05:59:27 EDT 2000


Hi again Horst.

It just occurred to me that another solution would just be to use a
cache (pretty much the same idea as I mentioned before, but the whole
thing could be handled within the __GetRowID function). I have tested
this, but note that I had to change the '__' prefixes to '_' as
otherwise I can't access the members from outside the class (I guess you
must have cut & pasted your original example).
Note that the only extra thing the class needs to do is initialise the
cache at startup ("self._rowCache = {}" in init()).

def __GetRowID (s, row):
        cacheKey = s._rowCache.get(row, None)
        if cacheKey is not None and s._rowDict[cacheKey]['data'] == row:
                return cacheKey

        for key in s._rowDict.keys():
                if s._rowDict[key]['data'] == row:
                        s._rowCache[row] = key
                        return key

The idea here is that if you're looking up a 'row' that you've looked up
before, the function has a pretty good idea of which key to try first -
but it does still check that the 'row' at that key is the one you're
after. If it's not, it drops back to your previous code (which updates
the cache when it finds the new value). As before, the potential size of
the cache is something you have to consider.
If 'None' is a value value for 'key' then choose an invalid 'key' value
where you see 'None' above (and you'll probably have to change the 'is
not' to '!=', depending on what you replace it with).

Cheers, Kev.

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