diff options
author | Salvatore Sanfilippo <antirez@gmail.com> | 2016-06-23 08:59:38 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2016-06-23 08:59:38 +0200 |
commit | 2fe9b7989792d1a722d5863734e379c15d57b56a (patch) | |
tree | 0487fa5f1e6403daacb8ae16d102a56881da3e06 | |
parent | 4e10b08fb3ead01e305b65f47180b44334bf9b8a (diff) | |
parent | 137fd86a6133b4a83c2a95215241c9906ec6877f (diff) | |
download | redis-2fe9b7989792d1a722d5863734e379c15d57b56a.tar.gz |
Merge pull request #3244 from dvirsky/optimize_autoMemoryFreed
Optimized autoMemoryFreed loop
-rw-r--r-- | src/module.c | 16 |
1 files changed, 12 insertions, 4 deletions
diff --git a/src/module.c b/src/module.c index 54f279075..ed178cecc 100644 --- a/src/module.c +++ b/src/module.c @@ -611,14 +611,22 @@ void autoMemoryFreed(RedisModuleCtx *ctx, int type, void *ptr) { if (!(ctx->flags & REDISMODULE_CTX_AUTO_MEMORY)) return; int j; - for (j = 0; j < ctx->amqueue_used; j++) { + for (j = ctx->amqueue_used - 1; j >= 0; j--) { if (ctx->amqueue[j].type == type && ctx->amqueue[j].ptr == ptr) { ctx->amqueue[j].type = REDISMODULE_AM_FREED; - /* Optimization: if this is the last element, we can - * reuse it. */ - if (j == ctx->amqueue_used-1) ctx->amqueue_used--; + + /* Switch the freed element and the top element, to avoid growing + * the queue unnecessarily if we allocate/free in a loop */ + if (j != ctx->amqueue_used-1) { + ctx->amqueue[j] = ctx->amqueue[ctx->amqueue_used-1]; + } + /* Reduce the size of the queue because we either moved the top + * element elsewhere or freed it */ + ctx->amqueue_used--; + + break; } } } |