S
S
Slavka2013-12-13 22:07:53
Python
Slavka, 2013-12-13 22:07:53

What is faster and what is smarter? (dictionary or...)

in general, for example, I will have a Client class with an id field in which the client's personal code will be stored, then I will have a list of these clients. I will contact clients by their personal code. So, what would be faster and more reasonable to search through the for loop, checking Client.id = code, or keep another dictionary in which there will be a code: number in the list, get a number from it and access the list?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mardy_bum, 2013-12-13
@mardy_bum

Of course O(1) dictionary lookup will be faster than O(n) linear lookup. But in this case, according to your scheme, you will have to keep both the list and the dictionary in memory at once, and also synchronize them while adding / removing elements. In my opinion, this is a very bad programming practice.
I would do one of these:
1) Initially use only a dictionary (id : Client) instead of a list
2) If your list of clients is sorted by id, you can do an O(log n) binary search
3) Why not store/retrieve data just don't use the db?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question