递归时间差(数字计算竟然比字符操作更耗时?)

首先是用获取团队下子集的方法:

static function getChild($user_id) {
    return Db::name('users')->where(['invite_user_id1' => $user_id])->column('user_id');
}

第一种方法:计数器

static function getTeamCount1($user_id) {
    $teamCount = 0;
    #如果人数为零 则停止搜索
    #查找子代 
    $child = self::getChild($user_id);
    if (count($child) != 0) {
        foreach ($child AS $v) {
            $teamCount ++;
            $teamCount += self::getTeamCount1($v); #$v的下级 
        }
    }
    return $teamCount;
}

第二种方法:数组形式


static function getTeamCount2($user_id) { 
    return count(self::getTeam($user_id));
}

static function getTeam($user_id) {
    $team = [];
    #如果人数为零 则停止搜索
    #查找子代 
    $child = self::getChild($user_id);
    if (count($child) != 0) {
        foreach ($child AS $v) {
            array_push($team, $v); #把当前用户放进下级列表
            $team = array_merge($team, self::getteam($v)); #$v的下级 
        }
    }
    return $team;
}

然后微秒计时:

        $user_id = 1;
        $s1 = microtime(true);
        $teamcount1 = UsersLogic::getTeamCount1($user_id);
        $e1 = microtime(true); 
        $t1 = $e1-$s1;
        $s2 = microtime(true);
        $teamcount2 = UsersLogic::getTeamCount2($user_id);[图片上传失败...(image-be226b-1542710054266)]

        $e2 = microtime(true); 
        $t2 = $e2-$s2;
        dd('t1:'.$t1."\nt2:".$t2);

输出结果如下:

t1:0.052999973297119
t2:0.031000137329102

递归时间差(数字计算竟然比字符操作更耗时?)_第1张图片

试了好几次,都是 t1t2大,为什么?

你可能感兴趣的:(递归时间差(数字计算竟然比字符操作更耗时?))