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

问题描述

限时删除!!

我很好奇执行字符串转换的最有效方法是什么.给定n个输入字符串和一组转换,通常哪种方法最有效?我目前使用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' => "\033[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基准测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:40