As you probably might have guessed, example 2 is faster, and the compiler does not do this for you.
Overview

Performance tests
Example # 1, a condition inside a loop:
Time taken: 0.2501 seconds
Time taken: 0.2336 seconds
Time taken: 0.2335 seconds
Time taken: 0.2319 seconds
Time taken: 0.2337 seconds
Average: 0.2364 seconds
And the code:
<?php
$list = array();
for ($i = 0; $i < 1000000; $i++) {
$list[] = md5(rand(0, 100000) * $i);
}
$a = microtime(true);
$test = 2;
foreach ($list as $listItem) {
if ($test == 1) {
$listItem .= " - one";
} else if ($test == 2) {
$listItem .= " - two";
} else if ($test == 3) {
$listItem .= " - three";
}
}
echo "Time taken: " . number_format(microtime(true) - $a, 4) . " seconds";
?>
Example # 2, a condition outside the loop:
Time taken: 0.1424 seconds
Time taken: 0.1426 seconds
Time taken: 0.1364 seconds
Time taken: 0.1348 seconds
Time taken: 0.1347 seconds
Average: 0.1382 seconds
And the code:
<?php
$list = array();
for ($i = 0; $i < 1000000; $i++) {
$list[] = md5(rand(0, 100000) * $i);
}
$a = microtime(true);
$test = 2;
if ($test == 1) {
foreach ($list as $listItem) {
$listItem .= " - one";
}
} else if ($test == 2) {
foreach ($list as $listItem) {
$listItem .= " - two";
}
} else if ($test == 3) {
foreach ($list as $listItem) {
$listItem .= " - three";
}
}
echo "Time taken: " . number_format(microtime(true) - $a, 4) . " seconds";
?>
, , , , int?
# 3, , :
Time taken: 0.1845 seconds
Time taken: 0.1821 seconds
Time taken: 0.1745 seconds
Time taken: 0.1777 seconds
Time taken: 0.1767 seconds
Average: 0.1791 seconds
:
<?php
$list = array();
for ($i = 0; $i < 1000000; $i++) {
$list[] = md5(rand(0, 100000) * $i);
}
$a = microtime(true);
$test = 2;
$result1 = ($test == 1);
$result2 = ($test == 2);
$result3 = ($test == 3);
foreach ($list as $listItem) {
if ($result1) {
$listItem .= " - one";
} else if ($result2) {
$listItem .= " - two";
} else if ($result3) {
$listItem .= " - three";
}
}
echo "Time taken: " . number_format(microtime(true) - $a, 4) . " seconds";
?>
. , , ββ array_walk?
# 4, array_walk:
Time taken: 0.4950 seconds
Time taken: 0.4946 seconds
Time taken: 0.4947 seconds
Time taken: 0.4937 seconds
Time taken: 0.4918 seconds
Average: 0.4940 seconds
:
<?php
function append_string($value, $suffix) {
return $value . $suffix;
}
$list = array();
for ($i = 0; $i < 1000000; $i++) {
$list[] = md5(rand(0, 100000) * $i);
}
$a = microtime(true);
$test = 2;
if ($test == 1) {
array_walk($list, "append_string", " - one");
} else if ($test == 2) {
array_walk($list, "append_string", " - two");
} else if ($test == 3) {
array_walk($list, "append_string", " - three");
}
echo "Time taken: " . number_format(microtime(true) - $a, 4) . " seconds";
?>
?! , C ++, , , .
/
# 1
# 1
# 2
# 2
# 3
# 3
# 4
# 4
- ( 100% ( β 1)). , - , 1,000,000 .
global .
PHP , , , , # 2, . , , # 1 # 3. , , , # 4.