IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

PHP中字符串截取的效率

PHPor 的Blog 2014-11-22 23:50:00 累计浏览 1,836 次
本机暂存

缘起

   如果你用PHP实现算法的话,效率可能会是比较关心的问题;对于大量的循环,循环体内任何一个操作都可能严重影响算法的效率,而字符串的截取也是最常见的操作;对于截取字符串中的一个字节的操作有两种写法:substr($string, $start, 1);  和 $string{$start}; 当然 $string{$start} 也可以写作 $string[$start]; 这里比较一下二者的效率。

测试

   

结论

   使用$string{$start}  是 使用substr($string, $start, 1); 的效率的10倍, 其实,前者写起来还更方便呢。

脚本

<?php
$str = 'abcd';
$time_start = microtime(1);
$i = 0;
while($i++<100000) {
	$str{2};
}
echo 'use $str{2}:',"\t\t\t", microtime(1) - $time_start , " s\n";
$time_start = microtime(1);
$i = 0;
while($i++<100000) {
	substr($str, 2, 1);
}
echo 'use substr($str, 2, 1):',"\t", microtime(1) - $time_start, ' s';
exit;

同分类推荐文章

  1. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,270)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,164)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,408)
  4. WEB系统需要关注的一些点 (累计阅读 18,219)
  5. 我的PHP,Python和Ruby之路 (累计阅读 13,149)
  6. include(“./file.php”)和include(“file.php”)区别 (累计阅读 12,790)
  7. 15个最好的免费开源电子商务平台 (累计阅读 12,541)
  8. Redis消息队列的若干实现方式 (累计阅读 12,088)
  9. 到底什么是MVC? (累计阅读 11,869)
  10. 关于memcache分布式一致性hash (累计阅读 11,820)