PHP中字符串截取的效率

PHPor 的Blog 2014-11-22 23:50:00 累计浏览 2,012 次

缘起

   如果你用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. NGINX 1.31.7: Native GeoIP2 support, HTTP/2 priorities, and QUIC improvements (2026-11-13 23:40:02)
  2. 说说广场 API 0.31.0 版的调用代码说明 (2026-11-13 19:10:02)
  3. NGINX Routing on HTTP Request Body (2026-10-27 14:10:42)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,702)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,568)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,821)
  4. WEB系统需要关注的一些点 (累计阅读 19,286)
  5. 我的PHP,Python和Ruby之路 (累计阅读 13,719)
  6. include(“./file.php”)和include(“file.php”)区别 (累计阅读 13,273)
  7. 15个最好的免费开源电子商务平台 (累计阅读 12,949)
  8. Redis消息队列的若干实现方式 (累计阅读 12,536)
  9. 到底什么是MVC? (累计阅读 12,384)
  10. 整理了一份招PHP高级工程师的面试题 (累计阅读 12,221)