php - Difference between incr and incrBy in Redis
PHP中文网
PHP中文网 2017-05-16 13:04:35
0
4
1123

I read online about their differences

But I tried it myself and found that incr can also specify the increment like incrby, so it feels like there is no difference. The picture below is the result of my test.

PHP中文网
PHP中文网

认证0级讲师

reply all(4)
阿神

The following is the Redis source code. In fact, the underlying implementation of incr and incrBy is consistent, but incrBy needs to do parameter verification

//incr命令
void incrCommand(redisClient *c) {
    incrDecrCommand(c,1);
}
//decr命令
void decrCommand(redisClient *c) {
    incrDecrCommand(c,-1);
}
//incrBy命令
void incrbyCommand(redisClient *c) {
    long long incr;

    if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
    incrDecrCommand(c,incr);
}
//decrby命令
void decrbyCommand(redisClient *c) {
    long long incr;

    if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
    incrDecrCommand(c,-incr);
}

It can be seen from here that incr does not support numeric parameters.

But why is $redis supported in PHP? Maybe the bottom layer of this library uses the incrBy command of redis

Peter_Zhu

The source code was posted wrong just now, please modify it


Looking through the source code of the phpredis extension, it should be compatible starting from 2.0.9.

When calling incr, optionally bring a long type number. If the number is not 1, call incrby.

By the way, when using incrBy, if the subsequent parameter is 1, incr will be called.

PHP_METHOD(Redis, incr){

    zval *object;
    RedisSock *redis_sock;
    char *key = NULL;
    int key_len;
    long val = 1;

    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l",
                                     &object, redis_ce,
                                     &key, &key_len, &val) == FAILURE) {
        RETURN_FALSE;
    }

    if(val == 1) {
        redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "INCR", 1);
    } else {
        redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "INCRBY", val);
    }
}
習慣沉默

http://redisdoc.com/string/in...
http://redisdoc.com/string/in...
Is the execution inside redis different? If you use incr to pass parameters, you need to execute the parameter specified times
But if you use incrby, you only need to perform one calculation, so you have to confirm it again

PHPzhong

After testing, no difference can be seen, the running time is the same, and there is no incr executed multiple times. If the number 23000000000000000000000000000 is executed multiple times, it will definitely take a certain amount of time, but it will take the same time as IncrBys

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template