Optimizations suggested and originally implemented by @oranagra. Re-applied by @antirez using the modified API.