donglanche9257 2018-05-25 09:04
浏览 47
已采纳

这种递归随机字符串生成在计算上是否昂贵?

I have created a function to generate a unique referral code for a user when they sign up, I want to ensure uniqueness so I check if it already exists, if it does then I call the function again recursively:

        public function generateUniqueReferralCode()
        {
            $referral_code = str_random(8);

            if(User::where('referral_code', $referral_code)->exists()) {
                $referral_code = $this->generateUniqueReferralCode();
            }

            return $referral_code;
        }

My question is, is this computationally expensive? Can it be done in a more efficient way as it has to scan the user table? Lets say we have 1 million users, it will check against 1 million user records if the key already exists.

  • 写回答

3条回答 默认 最新

  • dowdw44426 2018-05-25 09:33
    关注

    PHP functions are pretty costly. So I think the following is a little faster (didn't benchmark):

    public function generateUniqueReferralCode() {
        $referral_code = str_random(8);
    
        while (User::where('referral_code', $referral_code)->exists()) {
            $referral_code = str_random(8);
        }
    
        return $referral_code;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!