summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSalvatore Sanfilippo <antirez@gmail.com>2016-06-23 08:59:38 +0200
committerGitHub <noreply@github.com>2016-06-23 08:59:38 +0200
commit2fe9b7989792d1a722d5863734e379c15d57b56a (patch)
tree0487fa5f1e6403daacb8ae16d102a56881da3e06
parent4e10b08fb3ead01e305b65f47180b44334bf9b8a (diff)
parent137fd86a6133b4a83c2a95215241c9906ec6877f (diff)
downloadredis-2fe9b7989792d1a722d5863734e379c15d57b56a.tar.gz
Merge pull request #3244 from dvirsky/optimize_autoMemoryFreed
Optimized autoMemoryFreed loop
-rw-r--r--src/module.c16
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;
}
}
}