题
在语言,如爪哇和C#串不可改变的和可以计算昂贵建立一个字符串的时间。在所说的语言、图书馆课,以减少这种费用如C# System.Text.StringBuilder
和Java java.lang.StringBuilder
.
不php(4或5;我感兴趣的两)分享这种限制?如果是这样,是否有类似的解决问题的办法提供?
解决方案
不,PHP中没有stringbuilder类的类型,因为字符串是可变的。
话虽如此,根据你正在做的事情,有不同的方法来建立一个字符串。
例如,echo将接受以逗号分隔的标记作为输出。
// This...
echo 'one', 'two';
// Is the same as this
echo 'one';
echo 'two';
这意味着您可以输出复杂的字符串而不实际使用连接,这会更慢
// This...
echo 'one', 'two';
// Is faster than this...
echo 'one' . 'two';
如果您需要在变量中捕获此输出,可以使用输出缓冲功能来执行此操作
另外,PHP的阵列性能非常好。如果你想做一个逗号分隔的值列表,只需使用implode()
$values = array( 'one', 'two', 'three' );
$valueList = implode( ', ', $values );
最后,请确保您熟悉 PHP的字符串类型,并且它是不同的分隔符,以及每个人的含义。
其他提示
我是好奇的关于这一点,所以我跑了一个测试。我用了下列代码:
<?php
ini_set('memory_limit', '1024M');
define ('CORE_PATH', '/Users/foo');
define ('DS', DIRECTORY_SEPARATOR);
$numtests = 1000000;
function test1($numtests)
{
$CORE_PATH = '/Users/foo';
$DS = DIRECTORY_SEPARATOR;
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
$a[] = sprintf('%s%sDesktop%sjunk.php', $CORE_PATH, $DS, $DS);
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 1: sprintf()\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
function test2($numtests)
{
$CORE_PATH = '/Users/shigh';
$DS = DIRECTORY_SEPARATOR;
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
$a[] = $CORE_PATH . $DS . 'Desktop' . $DS . 'junk.php';
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 2: Concatenation\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
function test3($numtests)
{
$CORE_PATH = '/Users/shigh';
$DS = DIRECTORY_SEPARATOR;
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
ob_start();
echo $CORE_PATH,$DS,'Desktop',$DS,'junk.php';
$aa = ob_get_contents();
ob_end_clean();
$a[] = $aa;
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 3: Buffering Method\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
function test4($numtests)
{
$CORE_PATH = '/Users/shigh';
$DS = DIRECTORY_SEPARATOR;
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
$a[] = "{$CORE_PATH}{$DS}Desktop{$DS}junk.php";
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 4: Braced in-line variables\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
function test5($numtests)
{
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
$CORE_PATH = CORE_PATH;
$DS = DIRECTORY_SEPARATOR;
$a[] = "{$CORE_PATH}{$DS}Desktop{$DS}junk.php";
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 5: Braced inline variables with loop-level assignments\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
test1($numtests);
test2($numtests);
test3($numtests);
test4($numtests);
test5($numtests);
...并得到了以下的结果。图像连接。显然,sprintf是最有效的方式做到这一点,无论是在时间和存储的消耗。编辑:图像在另一个标签,除非你有鹰的愿景。
当您进行定时比较时,差异非常小,不太相关。自从选择使您的代码更易于阅读和理解之后,它会做得更多。
PHP中不需要StringBuilder模拟。
我做了几个简单的测试:
PHP中的:
$iterations = 10000;
$stringToAppend = 'TESTSTR';
$timer = new Timer(); // based on microtime()
$s = '';
for($i = 0; $i < $iterations; $i++)
{
$s .= ($i . $stringToAppend);
}
$timer->VarDumpCurrentTimerValue();
$timer->Restart();
// Used purlogic's implementation.
// I tried other implementations, but they are not faster
$sb = new StringBuilder();
for($i = 0; $i < $iterations; $i++)
{
$sb->append($i);
$sb->append($stringToAppend);
}
$ss = $sb->toString();
$timer->VarDumpCurrentTimerValue();
在C#(.NET 4.0)中:
const int iterations = 10000;
const string stringToAppend = "TESTSTR";
string s = "";
var timer = new Timer(); // based on StopWatch
for(int i = 0; i < iterations; i++)
{
s += (i + stringToAppend);
}
timer.ShowCurrentTimerValue();
timer.Restart();
var sb = new StringBuilder();
for(int i = 0; i < iterations; i++)
{
sb.Append(i);
sb.Append(stringToAppend);
}
string ss = sb.ToString();
timer.ShowCurrentTimerValue();
<强>结果:强>
10000次迭代:
1)PHP,普通级联:~6ms
2)PHP,使用StringBuilder:~5 ms
3)C#,普通级联:~520ms
4)C#,使用StringBuilder:~1ms
100000次迭代:
1)PHP,普通串联:~63ms
2)PHP,使用StringBuilder:~555ms
3)C#,普通级联:~91000ms // !!!
4)C#,使用StringBuilder:~17ms
我知道你在说什么。我刚刚创建了这个简单的类来模拟Java StringBuilder类。
class StringBuilder {
private $str = array();
public function __construct() { }
public function append($str) {
$this->str[] = $str;
}
public function toString() {
return implode($this->str);
}
}
PHP字符串是可变的。您可以更改这样的特定字符:
$string = 'abc';
$string[2] = 'a'; // $string equals 'aba'
$string[3] = 'd'; // $string equals 'abad'
$string[5] = 'e'; // $string equals 'abad e' (fills character(s) in between with spaces)
你可以将字符附加到这样的字符串:
$string .= 'a';
是。他们是这样。例如,如果要将几个字符串回显在一起,请使用
echo str1,str2,str3
而不是
echo str1.str2.str3让它快一点。
我在这篇文章末尾编写了代码来测试字符串连接的不同形式,它们在内存和时间足迹上几乎完全相同。
我使用的两个主要方法是将字符串连接在一起,并用字符串填充数组,然后将它们插入。我在php 5.6中使用1MB字符串添加了500个字符串添加(因此结果是500MB字符串)。 在测试的每次迭代中,所有内存和时间足迹都非常接近(在〜$ IterationNumber * 1MB)。两个测试的运行时间分别是50.398秒和50.843秒,这很可能在可接受的误差范围内。
不再引用的字符串的垃圾收集似乎非常直接,即使没有离开范围。由于字符串是可变的,因此事后不需要额外的内存。
HOWEVER ,以下测试显示,峰值内存使用量不同 WHILE 正在连接字符串。
$OneMB=str_repeat('x', 1024*1024);
$Final=$OneMB.$OneMB.$OneMB.$OneMB.$OneMB;
print memory_get_peak_usage();
结果= 10,806,800字节(初始PHP内存占用量约为10MB)
$OneMB=str_repeat('x', 1024*1024);
$Final=implode('', Array($OneMB, $OneMB, $OneMB, $OneMB, $OneMB));
print memory_get_peak_usage();
结果= 6,613,320字节(初始PHP内存占用量约为6MB)
事实上,在内存方面非常大的字符串连接中存在显着差异(我在创建非常大的数据集或SQL查询时遇到过这样的例子)。
但即使这个事实也有争议,具体取决于数据。例如,将1个字符连接到字符串以获得5000万字节(因此5000万次迭代)在5.97秒内占用最大量50,322,512字节(~48MB)。虽然做数组方法最终使用7,337,107,176字节(~6.8GB)在12.1秒内创建数组,然后花费额外的4.32秒来组合数组中的字符串。
Anywho ...下面是我在开头提到的基准代码,它显示了方法几乎相同。它输出一个漂亮的HTML表。
<?
//Please note, for the recursion test to go beyond 256, xdebug.max_nesting_level needs to be raised. You also may need to update your memory_limit depending on the number of iterations
//Output the start memory
print 'Start: '.memory_get_usage()."B<br><br>Below test results are in MB<br>";
//Our 1MB string
global $OneMB, $NumIterations;
$OneMB=str_repeat('x', 1024*1024);
$NumIterations=500;
//Run the tests
$ConcatTest=RunTest('ConcatTest');
$ImplodeTest=RunTest('ImplodeTest');
$RecurseTest=RunTest('RecurseTest');
//Output the results in a table
OutputResults(
Array('ConcatTest', 'ImplodeTest', 'RecurseTest'),
Array($ConcatTest, $ImplodeTest, $RecurseTest)
);
//Start a test run by initializing the array that will hold the results and manipulating those results after the test is complete
function RunTest($TestName)
{
$CurrentTestNums=Array();
$TestStartMem=memory_get_usage();
$StartTime=microtime(true);
RunTestReal($TestName, $CurrentTestNums, $StrLen);
$CurrentTestNums[]=memory_get_usage();
//Subtract $TestStartMem from all other numbers
foreach($CurrentTestNums as &$Num)
$Num-=$TestStartMem;
unset($Num);
$CurrentTestNums[]=$StrLen;
$CurrentTestNums[]=microtime(true)-$StartTime;
return $CurrentTestNums;
}
//Initialize the test and store the memory allocated at the end of the test, with the result
function RunTestReal($TestName, &$CurrentTestNums, &$StrLen)
{
$R=$TestName($CurrentTestNums);
$CurrentTestNums[]=memory_get_usage();
$StrLen=strlen($R);
}
//Concatenate 1MB string over and over onto a single string
function ConcatTest(&$CurrentTestNums)
{
global $OneMB, $NumIterations;
$Result='';
for($i=0;$i<$NumIterations;$i++)
{
$Result.=$OneMB;
$CurrentTestNums[]=memory_get_usage();
}
return $Result;
}
//Create an array of 1MB strings and then join w/ an implode
function ImplodeTest(&$CurrentTestNums)
{
global $OneMB, $NumIterations;
$Result=Array();
for($i=0;$i<$NumIterations;$i++)
{
$Result[]=$OneMB;
$CurrentTestNums[]=memory_get_usage();
}
return implode('', $Result);
}
//Recursively add strings onto each other
function RecurseTest(&$CurrentTestNums, $TestNum=0)
{
Global $OneMB, $NumIterations;
if($TestNum==$NumIterations)
return '';
$NewStr=RecurseTest($CurrentTestNums, $TestNum+1).$OneMB;
$CurrentTestNums[]=memory_get_usage();
return $NewStr;
}
//Output the results in a table
function OutputResults($TestNames, $TestResults)
{
global $NumIterations;
print '<table border=1 cellspacing=0 cellpadding=2><tr><th>Test Name</th><th>'.implode('</th><th>', $TestNames).'</th></tr>';
$FinalNames=Array('Final Result', 'Clean');
for($i=0;$i<$NumIterations+2;$i++)
{
$TestName=($i<$NumIterations ? $i : $FinalNames[$i-$NumIterations]);
print "<tr><th>$TestName</th>";
foreach($TestResults as $TR)
printf('<td>%07.4f</td>', $TR[$i]/1024/1024);
print '</tr>';
}
//Other result numbers
print '<tr><th>Final String Size</th>';
foreach($TestResults as $TR)
printf('<td>%d</td>', $TR[$NumIterations+2]);
print '</tr><tr><th>Runtime</th>';
foreach($TestResults as $TR)
printf('<td>%s</td>', $TR[$NumIterations+3]);
print '</tr></table>';
}
?>
首先,如果您不需要连接字符串,请不要这样做:它总是会更快地完成
echo $a,$b,$c;
大于
echo $a . $b . $c;
但是,至少在PHP5中,字符串连接真的非常快,特别是如果只有一个对给定字符串的引用。我想解释器在内部使用 StringBuilder
类技术。
如果你在PHP字符串中放置变量值,我明白使用内联变量包含它会更快一些(这不是它的官方名称 - 我不记得是什么)
$aString = 'oranges';
$compareString = "comparing apples to {$aString}!";
echo $compareString
comparing apples to oranges!
必须在双引号内才能正常工作。也适用于数组成员(即
echo "You requested page id {如果你在PHP字符串中放置变量值,我明白使用内联变量包含它会更快一些(这不是它的官方名称 - 我不记得是什么)
$aString = 'oranges';
$compareString = "comparing apples to {$aString}!";
echo $compareString
comparing apples to oranges!
必须在双引号内才能正常工作。也适用于数组成员(即
<*>
)
POST['id']}";
)
在php中没有这样的限制, php可以使用点(。)运算符
连接字符串$a="hello ";
$b="world";
echo $a.$b;
输出“hello world”