PHP strtr 与 str_replace 基准测试 [英] PHP strtr vs str_replace benchmarking

查看:34
本文介绍了PHP strtr 与 str_replace 基准测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇进行字符串转换的最高效方法是什么.给定一个输入字符串和一组翻译,一般来说哪种方法最有效?我目前使用 strtr(),但已经测试了各种循环方法,str_replace() 与数组等.strtr() 方法基准测试我的系统上最快的,具体取决于翻译,但我很好奇是否有我还没有想到的更快的方法.

I'm curious what the most performant method of doing string transformations is. Given a n input string and a set of translations, what method is the most efficient in general? I currently use strtr(), but have tested various looping methods, str_replace() with an array, etc. The strtr() method benchmarks the fastest on my system, depending on the translations, but I'm curious if there are faster methods I haven't thought of yet.

如果相关,我的特定用例涉及将 2 字节字符串转换为终端的 ANSI 颜色序列.示例:

If it's pertinent, my particular use case involves transforming 2-byte strings into ANSI color sequences for a terminal. Example:

// In practice, the number of translations is much greater than one...
$out = strtr("|rThis should be red", array('|r' => "33[31m"));

推荐答案

对于简单的替换,strtr 似乎更快,但是当你有很多搜索字符串的复杂替换时,str_replace 有优势.

For simple replacements, strtr seems to be faster, but when you have complex replacements with many search strings, it appears that str_replace has the edge.

这篇关于PHP strtr 与 str_replace 基准测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆