search
HomeBackend DevelopmentPHP TutorialPHP有没有必要实现stringbuilder

本人刚刚毕业,也是从C#转来,在学习PHP的过程中发现PHP没有类似C#一样的stringbuilder类型。
因为我知道在C#中多次操作字符串用stringbuilder的效率要高过string,那么想问下PHP为什么没有实现stringbuilder?
还有,如果我自己用数组模拟stringbuilder的话会提高效率么?


回复讨论(解决方案)

你可以自己去测试下,感觉没啥区别,指不定还会占用更高的内存开销不划算。

字符串比??模拟快多了。
字符串

$starttime = getMicrotime();$str = '';for($i=0;$i<100000;$i++){    $str .= $i;}$endtime = getMicrotime();printf("run time %f ms\r\n", (float)($endtime-$starttime)*1000); function getMicrotime(){    list($usec, $sec) = explode(' ', microtime());    return (float)$usec + (float)$sec;}

run time 61.100006 ms

数组
$starttime = getMicrotime();$arr = array();for($i=0;$i<100000;$i++){    array_push($arr, $i);}$endtime = getMicrotime();printf("run time %f ms\r\n", (float)($endtime-$starttime)*1000);function getMicrotime(){    list($usec, $sec) = explode(' ', microtime());    return (float)$usec + (float)$sec;}

run time 200.176954 ms

找到了原理解释:
PHP中所有的变量在底层都是同一种结构 Zval。通过Zval结构可以看出,在PHP中,字符串是由由指向实际数据的指针和长度结构体组成,这点和c++中的string比较类似。由于通过一个实际变量表示长度,和c不同,它的字符串可以是2进制数据(包含\0),同时在PHP中,求字符串长度strlen是O(1)操作。
在新增、修改、追加字符串操作时,PHP都会重新分配内存生成新的字符串。最后,出于安全考虑,PHP在生成一个字符串时末尾仍然会添加\0。
常见的字符串拼接方式及速度比较:

假设有如下4个变量:$strA=‘123’; $strB = ‘456’; $intA=123; intB=456;

现在对如下的几种字符串拼接方式做一个比较和说明:
1 $res = $strA.$strB和$res = “$strA$strB”
2 这种情况下,zend会重新malloc一块内存并进行相应处理,其速度一般
3 $strA = $strA.$strB
4 这种是速度最快的,zend会在当前strA基础上直接relloc,避免重复拷贝
5 $res = $intA.$intB
6 这种速度较慢,因为需要做隐式的格式转换,实际编写程序中也应该注意尽量避免
7 $strA = sprintf (“%s%s”,$strA.$strB);
8 这会是最慢的一种方式,因为sprintf在PHP中并不是一个语言结构,本身对于格式识别和处理就需要耗费比较多时间,另外本身机制也是malloc。不过sprintf的方式最具可读性,实际中可以根据具体情况灵活选择。


【PS:因为PHP中string类型的实现其实就是C#和Java中的stringbuilder,其本身在对自身拓展时并不会重新分配内存赋值而是在已有内存基础上通过malloc动态分配内存,所以PHP中的string虽然和C#以及Java中的string用法相似,但原理上却是stringbuilder】

字符串比??模拟快多了。
字符串

$starttime = getMicrotime();$str = '';for($i=0;$i<100000;$i++){    $str .= $i;}$endtime = getMicrotime();printf("run time %f ms\r\n", (float)($endtime-$starttime)*1000); function getMicrotime(){    list($usec, $sec) = explode(' ', microtime());    return (float)$usec + (float)$sec;}

run time 61.100006 ms

数组
$starttime = getMicrotime();$arr = array();for($i=0;$i<100000;$i++){    array_push($arr, $i);}$endtime = getMicrotime();printf("run time %f ms\r\n", (float)($endtime-$starttime)*1000);function getMicrotime(){    list($usec, $sec) = explode(' ', microtime());    return (float)$usec + (float)$sec;}

run time 200.176954 ms


同样感谢,还写了代码给我解释
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft