Skip to content

Commit

Permalink
Merge pull request redis#3244 from dvirsky/optimize_autoMemoryFreed
Browse files Browse the repository at this point in the history
Optimized autoMemoryFreed loop
  • Loading branch information
antirez committed Jun 23, 2016
2 parents aa345bf + 137fd86 commit 574fc36
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/module.c
Expand Up @@ -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;
}
}
}
Expand Down

0 comments on commit 574fc36

Please sign in to comment.