5đź‘Ť
Remember, redis is not a general purpose database. There are some queries or uses where an old-fashioned rdbms is the way to go, and some where redis outclasses the rdbms. Redis gives you lightning-fast reads and writes to key-value stored data. i.e., “For a given word, I want to retrieve the number of occurrences”, not “I want all of the words sorted by occurrence.”
So, for example:
def prep_redis():
for word in Word.objects.all():
redis_server.set(word.name, word.occurrence)
def test_lookup_postgres(name):
# start = datetime.datetime.now()
p = Word.objects.get(name=name)
# end = datetime.datetime.now()
# diff = end - start
# print('postgres took %s ms' % (diff * 1000,))
return p.occurrence
def test_lookup_redis(name):
# start = datetime.datetime.now()
value = redis_server.get(name)
# end = datetime.datetime.now()
# diff = end - start
# print('redis took %s ms' % (diff * 1000,))
return value
def main():
from timeit import Timer
prep_redis()
r_timer = Timer(lambda: test_lookup_redis('sesame'))
p_timer = Timer(lambda: test_lookup_postgres('sesame'))
print('For 1000 runs, redis: %s' % (r_timer.timeit(number=1000),))
print('For 1000 runs, postgres: %s' % (p_timer.timeit(number=1000),))
Here we will expect redis to be faster than postgres.
In contrast, redis is remarkably slow with larger data structures because the time it takes to serialize and deserialize the data overwhelms the I/O cost:
Speed of RAM and memory bandwidth seem less critical for global performance especially for small objects. For large objects (>10 KB), it may become noticeable though. Usually, it is not really cost-effective to buy expensive fast memory modules to optimize Redis.
Redis benchmarks
1đź‘Ť
Your test is constructing the database query but is not actually executing it. Change your line to:
words = list(Word.objects.order_by('-occurrence'))
That will force evaluation of the query. (See this section of the documentation for more details.)
- [Django]-Django step through the code
- [Django]-How to add if statement in filter?
- [Django]-Admin site list vs tuple django