【发布时间】:2012-09-28 14:25:57
【问题描述】:
【问题讨论】:
-
保存在字符串中的数组?你能举个这个数组的例子吗?
-
@Ikke:我认为他的意思是他希望将数组的第一项保存在字符串中。数组不能保存在字符串中。
标签: php arrays performance
【问题讨论】:
标签: php arrays performance
像这样?:
$firstitem = $array[0];
【讨论】:
使用reset:
<?php
$array = Array(0 => "hello", "w" => "orld");
echo reset($array);
// Output: "hello"
?>
注意,当你使用这个时,数组的光标会设置在数组的开头。
(当然,您可以将结果存储为字符串而不是echoing,但我使用echo 进行演示。)
【讨论】:
begin() :)
我会说这是非常优化的:
echo reset($arr);
【讨论】:
【讨论】:
最有效的是获取引用,所以不涉及字符串复制:
$first = &$array[0];
请确保您不要修改$first,因为它也会在数组中被修改。如果您必须修改它,请寻找其他答案替代方案。
【讨论】:
我只能试试这个
$max = 2000;
$array = range(1, 2000);
echo "<pre>";
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = current($array);
}
echo microtime(true) - $start ,PHP_EOL;
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = reset($array);
}
echo microtime(true) - $start ,PHP_EOL;
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = $array[0];
}
echo microtime(true) - $start ,PHP_EOL;
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = &$array[0];
}
echo microtime(true) - $start ,PHP_EOL;
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = array_shift($array);
}
echo microtime(true) - $start ,PHP_EOL;
输出
0.03761100769043
0.037437915802002
0.00060200691223145 <--- 2nd Position
0.00056600570678711 <--- 1st Position
0.068138122558594
所以最快的是
$item = &$array[0];
【讨论】: