vendredi 25 mai 2018

Is this recursive random string generation computationally expensive?

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire