Bug #67124 [Com]: Typecast (bool) $array slowdown according to array length
| From: | vovan-ve at yandex dot ru | Date: | Sat, 26 Apr 2014 12:59:57 +0000 |
| Subject: | Bug #67124 [Com]: Typecast (bool) $array slowdown according to array length | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-185455@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=67124&edit=1
ID: 67124
Comment by: vovan-ve at yandex dot ru
Reported by: vovan-ve at yandex dot ru
Summary: Typecast (bool) $array slowdown according to array
length
Status: Open
Type: Bug
Package: Performance problem
Operating System: Linux
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
Yes, "workaround" to pass thru the bugs maze. Welcome to PHP. Did you expect something
else?..
Previous Comments:
------------------------------------------------------------------------
[2014-04-26 09:43:59] hanskrentel at yahoo dot de
The workaround is to first count with arrays as the count is cached.
(bool) count($array);
------------------------------------------------------------------------
[2014-04-24 04:47:35] vovan-ve at yandex dot ru
Looks like array is copied while casting:
# memory_limit=1G
echo "Create array...";
$array = array_fill(0, 10 * 1000 * 1000, null);
echo " ok\nCasting...";
$start = microtime(true);
(bool) $array;
printf(" %.3F sec.\n", microtime(true) - $start);
Output:
Create array... ok
Casting...Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 35
bytes) in ...
------------------------------------------------------------------------
[2014-04-24 03:55:47] vovan-ve at yandex dot ru
More clear test cases:
$tests = array(
'empty' => array(),
'x10' => range(1, 10),
'x100' => range(1, 100),
'x1000' => range(1, 1000),
);
Result:
empty 0.15 sec. total
x10 0.65 sec. total
x100 5.14 sec. total
x1000 49.91 sec. total
------------------------------------------------------------------------
[2014-04-24 03:09:36] vovan-ve at yandex dot ru
Description:
------------
Casting non-empty array to boolean using (bool) takes a time with respect to array length. There are
no reasons for this. This is abnormal.
Any other checks like
if ($array), ($array) ?:, [] === $array
and so on are not affected.
At least whole PHP 5 is affected by this issue.
Test script:
---------------
$tests = array(
'$empty' => array(),
'$full' => range(1, 1000),
);
$count = 1 * 1000 * 1000;
foreach ($tests as $name => $array) {
printf("%-10s", $name);
$start = microtime(true);
$i = $count;
while ($i-- > 0) {
(bool) $array;
}
$total = microtime(true) - $start;
printf("%6.2F sec. total\n", $total, $total / $count);
}
Actual result:
--------------
$empty 0.15 sec. total
$full 52.03 sec. total
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=67124&edit=1