Merge pull request #3244 from dvirsky/optimize_autoMemoryFreed

Optimized autoMemoryFreed loop
This commit is contained in:
Salvatore Sanfilippo 2016-06-23 08:59:38 +02:00 committed by GitHub
commit 2fe9b79897

View File

@ -611,14 +611,22 @@ void autoMemoryFreed(RedisModuleCtx *ctx, int type, void *ptr) {
if (!(ctx->flags & REDISMODULE_CTX_AUTO_MEMORY)) return; if (!(ctx->flags & REDISMODULE_CTX_AUTO_MEMORY)) return;
int j; 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 && if (ctx->amqueue[j].type == type &&
ctx->amqueue[j].ptr == ptr) ctx->amqueue[j].ptr == ptr)
{ {
ctx->amqueue[j].type = REDISMODULE_AM_FREED; ctx->amqueue[j].type = REDISMODULE_AM_FREED;
/* Optimization: if this is the last element, we can
* reuse it. */ /* Switch the freed element and the top element, to avoid growing
if (j == ctx->amqueue_used-1) ctx->amqueue_used--; * 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;
} }
} }
} }