TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

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

8 点作者 magnetikonline大约 11 年前

3 条评论

AaronFriel大约 11 年前
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.
Mithaldu大约 11 年前
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 未加载
krapp大约 11 年前
That is interesting...I would have assumed concatenating arrays was slower anyway.<p>Would it be relevant to test this using file reads?
评论 #7445571 未加载