TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Trival PHP string concatenation benchmarks, proving time better spent elsewhere.

8 pointsby magnetikonlineabout 11 years ago

3 comments

AaronFrielabout 11 years ago
This benchmark measures the time to generate random characters - per Mithaldu&#x27;s remark - not the time to shuffle bytes around. If it actually took around 7 seconds to shuffle about 20 megabytes[1] of data around, no one would use PHP for anything. Of course, the algorithm actually performs 20 million string concatenations, because of the way random strings are generated.<p>To give you an idea of how slow that is, maximum memory throughput with memcpy on many modern systems is measured in the tens of gigabytes per second. The comparison to .NET at the end is amusing, because the same benchmark including the random generation of characters can be done many times faster in C#. And I&#x27;m not even good at writing C#, having spent most of my time in Haskell. But I did it anyway.<p><pre><code> PHP version (in C#) = 1.8660s Using prebuilt array = 0.0654s Using StringBuilder, random = 1.5628s Using StringBuilder, array = 0.0749s </code></pre> EDIT: If I construct the StringBuilder with a size parameter, it shaves another 0.02 seconds off (or 25% of execution time).<p>Gist for source: <a href="https://gist.github.com/AaronFriel/9699764" rel="nofollow">https:&#x2F;&#x2F;gist.github.com&#x2F;AaronFriel&#x2F;9699764</a><p>The original should be rewritten to not be a test of PRNG throughput. In the amount of time that it took PHP to generate those random strings, my unoptimized, first-try C# concatenates about a hundred times faster.<p>[1]I am aware that this is merely the size of the resultant string - 20 characters times 1,000,000 iterations. But it&#x27;s within a factor of two of the total bytes copied, and I don&#x27;t know PHP&#x27;s internal string representation. I don&#x27;t know if each append alters an entire string, rewrites a rope structure, etc. In all likelihood, many fewer than 20 million bytes were harmed by PHP in the making of this benchmark.
Mithalduabout 11 years ago
Sans per-call profiling i&#x27;d expect the string concatenation time to be dwarved by the calls to rand.<p>Edit: Does PHP even have any per-call profilers?
评论 #7447389 未加载
krappabout 11 years ago
That is interesting...I would have assumed concatenating arrays was slower anyway.<p>Would it be relevant to test this using file reads?
评论 #7445571 未加载