2 months ago I started working on an ORM for Redis a key-value database. Now I am about to rewrite parts of it because I didn't test and measure everything beforehand.
This time I decided to measure the performance of the different Redis commands. I want to be sure that any optimizations I might implement really helps.
A Redis database is a big mapping. Its keys are strings and the values can be strings, lists, sets, ordered sets, and hashes. Here I’ll just consider strings and hashes. The 2 types of commands I'm interested in are:
- Set commands: SET, MSET, HMSET, and HSET.
- Get commands: GET, MGET, HMGET, and HGET.
The command prefixed by H are for hashes, the ones without prefix are for regular strings. Commands with an M are the ones that can set or get multiple values. To learn more about how Redis works check out the documentation.
I wrote a little script to test how fast the different commands are depending on the number of items to write or read for each operation. I configured Redis to use the Append-only-file like this:
appendonly yes appendfsync always
Write operations will surely be faster without it. but that's how I use Redis. I do this because I don’t want to lose data, ever!
Here are the results:
Hash operations are a little bit faster than the ones on strings, probably because there are fewer keys in a hash than in the full Redis mapping. The difference is not too significant though.
*SET operations are faster than *MSET operations for a single element, and for 2 elements or more *MSET operations are faster. No surprise here. But something worth noting is that *MSET operations are MUCH faster than *SET operations with 2 or more elements. They can be as much as 5 times faster when reading and 9 times faster when writing. Something to keep in mind when you have to update 5000 keys in a single batch.