Reputation: 699
I have to store 300+ Objects (users) in memory and get those users according to their ID. What is the most efficient way to do this?
Currently i'm storing the objects in a list, to get a user from the list i use this code:
[u for u in users if u.id == id]
This doesn't seem to be very efficient as i have to iterate over the whole list in the worst case.
Upvotes: 0
Views: 1985
Reputation: 9323
Or use generators
instead of using a list comprehension dict use a tuple
(u for u in users if u.id == id)
EDIT
If the ids are unique my solution has nothing to do, the dict one is better, but it the issue is performance related the generator way has a good performance peak, like my performance test will show :
import timeit
setup = """
from random import randint
class User:
id = randint(0,10000)
users = [User() for _ in range(0,100)]
def generator_sample(users):
final = (u for u in users if u.id == 100)
def list_sample(users):
final = [u for u in users if u.id == 100]
"""
print timeit.timeit('generator_sample(users)', setup=setup) # 0.413088083267
print timeit.timeit('list_sample(users)', setup=setup) # 4.37370610237
Upvotes: 2
Reputation: 454
Create a dict.
users = {}
add the values of each user as follows.
users[user_id] = "user_value"
You may just extract the particular record via the user id as
users[user_id]
You may store this either in mongo or store it using pickle.
Upvotes: 4