php 如何创建uuid
传统的创建uuid的方法是自己写个函数实现随机
<?php function create_uuid($prefix="") { $chars = md5(uniqid(mt_rand(), true)); $uuid = substr ( $chars, 0, 8 ) . '-' . substr ( $chars, 8, 4 ) . '-' . substr ( $chars, 12, 4 ) . '-' . substr ( $chars, 16, 4 ) . '-' . substr ( $chars, 20, 12 ); return $prefix.$uuid ; } $uuid = create_uuid(); var_dump($uuid);
不过现在有扩展了 就使用扩展吧
使用 apt search uuid 搜索一下
sudo apt search uuid
得到结果
然后就安装吧
使用命令
sudo apt-get install php7.4-uuid
安装
$ sudo apt-get install php7.4-uuid Reading package lists... Done Building dependency tree Reading state information... Done Note, selecting 'php-uuid' instead of 'php7.4-uuid' The following NEW packages will be installed: php-uuid 0 upgraded, 1 newly installed, 0 to remove and 95 not upgraded. Need to get 8,520 B of archives. After this operation, 51.2 kB of additional disk space will be used. Get:1 http://cn.archive.ubuntu.com/ubuntu focal/universe amd64 php-uuid amd64 1.1.0-1build1 [8,520 B] Fetched 8,520 B in 1s (14.4 kB/s) Selecting previously unselected package php-uuid. (Reading database ... 222525 files and directories currently installed.) Preparing to unpack .../php-uuid_1.1.0-1build1_amd64.deb ... Unpacking php-uuid (1.1.0-1build1) ... Setting up php-uuid (1.1.0-1build1) ... Processing triggers for libapache2-mod-php7.4 (7.4.3-4ubuntu2.4) ... Processing triggers for php7.4-cli (7.4.3-4ubuntu2.4) ...
可以看到此时扩展已经有了
$ php -m |grep uuid uuid
web 端需要 sudo /etc/init.d/apache2 restart 一下
然后 phpinfo()
之后使用php 函数 uuid_create 即可。
<?php $uuid = uuid_create(1); var_dump($uuid);
cli 端得到
string(36) "a84f0c4e-a24b-11eb-87fd-9f2061574580"
web 端得到
经过测试发现还是扩展的方式实现更快。
传统方式实现uuid 100万次
代码
<?php function create_uuid($prefix="") { $chars = md5(uniqid(mt_rand(), true)); $uuid = substr ( $chars, 0, 8 ) . '-' . substr ( $chars, 8, 4 ) . '-' . substr ( $chars, 12, 4 ) . '-' . substr ( $chars, 16, 4 ) . '-' . substr ( $chars, 20, 12 ); return $prefix.$uuid ; } $start_time = microtime(true); for ($i=0; $i < 1000000; $i++) { $uuid = create_uuid(1); } $end_time = microtime(true); var_dump(($end_time-$start_time)); exit;
效果
扩展实现
<?php $start_time = microtime(true); for ($i=0; $i < 1000000; $i++) { $uuid = uuid_create(1); } $end_time = microtime(true); var_dump(($end_time-$start_time)); exit;
效率几乎提升一倍啊!看来还是扩展厉害啊,毕竟扩展都底层语言了嘛。
不过单次执行一次来看时间几乎可以忽略不计
传统方式得到的时间是 4.9829483032227E-5
扩展方式得到的时间是 2.6941299438477E-5
但是单次的这个耗时对比极不稳定,有时候传统方式用时反而短,这个扩展有时候时间也用的长,这说明单次其实两者并没有太大差异。而如果这个东西用到了百次 、万次循环的时候,它使用扩展就很有用了。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析