shshank
shshank

Reputation: 2641

Using dicts or making classes? which is faster?

I get a multi level dict object, which I have to process. By multi level I mean the top level dict has some keys with dicts as value.

e.g.

{'l1key1' : 'value1'
 'l1key2' : {
             'l2key1': 'something'
             'l2key2': {
                        'l3key1': 'something' 
                        'l3key2': 'something else'
                       }
            }
 'l1key3' : 'some other value'
}

The actual dict is huge. It has some 10+ keys and 4 levels. Sometimes some optional keys might be missing.

I made classes to keep the code organized. e.g

Class Level3():
    def __init__(self, l3dict):
        if not l3dict:
            self.exists = False
        else:
            self.exists = True
            self.l3key1 = l3dict.get('l3key1') 
            self.l3key2 = l3dict.get('l3key2')

Class Level2():
    def __init__(self, l2dict):
        if not l2dict:
            self.exists = False
        else:
            self.exists = True
            self.l2key1 = l2dict.get('l2key1') 
            self.l2key2 = Level3(l3dict.get('l2key2'))

Class Level1():
    def __init__(self, mydict):
            self.l1key1 = mydict.get('l1key1') 
            self.l1key2 = Level2(mydict.get('l1key2'))
            self.l1key3 = mydict.get('l1key3')


#usage
mydict = json.loads(thejson)     #the json I am getting as input
myobject = Level1(mydict)

My question is should I use the dict directly in my script instead of making the classes?

Having low execution time is important. Will initializing the classes from the dict make it slow?

Edit:: I timed it. the initialization of the class takes 80 microseconds on average, The application has to complete all the processing within 250 milliseconds. I will now have to see time taken by the processing to determine if I can afford the 80 microseconds.

Thankyou for the answers. I will also be using Cython for processing the data.

Upvotes: 1

Views: 169

Answers (1)

Shashank
Shashank

Reputation: 13869

Just to get this question answered, using just using the dicts that you've already set up would be faster. Creating objects, even trivial ones, in CPython is extremely costly as I've stated in the comments.

Upvotes: 1

Related Questions