Skip to content

Commit

Permalink
minor #53963 [Uid] Optimize UuidV4 generation (smnandre)
Browse files Browse the repository at this point in the history
This PR was squashed before being merged into the 7.1 branch.

Discussion
----------

[Uid] Optimize UuidV4 generation

| Q             | A
| ------------- | ---
| Branch?       | 7.1
| Bug fix?      | no
| New feature?  | no
| Deprecations? | no
| Issues        | Fix #
| License       | MIT

I tried to optimize as much as I could the [UuidV4 generation](https://github.com/symfony/symfony/blob/7.1/src/Symfony/Component/Uid/UuidV4.php).

According to local tests, the code is now between `35%` and `40%` faster.

(But to be fair... we are talking nanoseconds here 😅)

Thanks `@nicolas`-grekas for the help in this ~~useless~~ fun quest  😃

--

--> Bench (& results): https://github.com/smnandre/uuid-bench

Commits
-------

7b5c57b [Uid] Optimize UuidV4 generation
  • Loading branch information
fabpot committed Feb 20, 2024
2 parents b6d7264 + 7b5c57b commit 86b07f0
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/Symfony/Component/Uid/UuidV4.php
Expand Up @@ -23,12 +23,19 @@ class UuidV4 extends Uuid
public function __construct(?string $uuid = null)
{
if (null === $uuid) {
$uuid = random_bytes(16);
$uuid[6] = $uuid[6] & "\x0F" | "\x40";
$uuid[8] = $uuid[8] & "\x3F" | "\x80";
$uuid = bin2hex($uuid);

$this->uid = substr($uuid, 0, 8).'-'.substr($uuid, 8, 4).'-'.substr($uuid, 12, 4).'-'.substr($uuid, 16, 4).'-'.substr($uuid, 20, 12);
// Generate 36 random hex characters (144 bits)
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
$uuid = bin2hex(random_bytes(18));
// Insert dashes to match the UUID format
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
$uuid[8] = $uuid[13] = $uuid[18] = $uuid[23] = '-';
// Set the UUID version to 4
// xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx
$uuid[14] = '4';
// Set the UUID variant: the 19th char must be in [8, 9, a, b]
// xxxxxxxx-xxxx-4xxx-?xxx-xxxxxxxxxxxx
$uuid[19] = ['8', '9', 'a', 'b', '8', '9', 'a', 'b', 'c' => '8', 'd' => '9', 'e' => 'a', 'f' => 'b'][$uuid[19]] ?? $uuid[19];
$this->uid = $uuid;
} else {
parent::__construct($uuid, true);
}
Expand Down

0 comments on commit 86b07f0

Please sign in to comment.