mardi 15 novembre 2016

Readability vs. Performance: call function multiple times or flatten them?

I have three class: User, Day, and Session.

Each User contains several Days. Each Day contains several Sessions. Each Session contains a sequence.

Now I have a function inside User called update, which is used to update the sequence at day date with session id guid. The new sequence is new_sequence.

First: One way of doing this is as following:

class User(object):
    """..."""
    def __init__(self, userid):
        logger.info("Initialize User: %s" % userid)
        self.userid = userid
        self.days = {}

    def update(self, date, guid, new_seq):
        """..."""
        theday = self.days.get(date, Day(userid, date))
        theday.update(guid, new_seq)
        self.days[date] = theday


class Day(object):
    """..."""
    def __init__(self, userid, date):
        logger.info("Initialize Day %s for User: %s" % (date, userid))
        self.userid = userid
        self.date = date
        self.sessions = {}

    def update(self, guid, new_seq):
        """..."""
        thesession = self.sessions.get(guid, Session(userid, date, guid))
        thesession.update(new_seq)
        self.sessions[guid] = thesession


class Session(object):
    """..."""
    def __init__(self, userid, date, guid, seq=None):
        logger.info("Initialize Session %s on Day %s for User: %s" %
                    (guid, date, userid))
        self.userid = userid
        self.date = date
        self.guid = guid
        # argument seq is None instead of [], avoiding mutable argument
        if seq is None:
            self.seq = []
        else:
            self.seq = seq
        self.mark = True

    def update(self, new_seq):
        """..."""
        self.seq.extend(new_seq)

However, this means update in User will call update in Day, which will call update in Session. I would like to know whether this will have very bad impact on the performance.

Second: On the other hand, I can do the following:

class User(object):
    """..."""
    def update(self, date, guid, new_seq):
        """..."""
        theday = self.days.get(date, Day(userid, date))
        theday.update(guid, new_seq)
        thesession = theday.sessions.get(guid, Session(userid, date, guid))
        thesession.seq.extend(new_seq)
        theday.sessions[guid] = thesession
        self.days[date] = theday

This is really with less readability and maintainability than the previous implementation.

I would like to known which one is a better trade-off (between readability and performance)? Or, there is actually not so much performance loss by having the first implementation.

Aucun commentaire:

Enregistrer un commentaire