note 127044 added to function.array-is-list
| From: | divinity76+spam at gmail dot com | Date: | Tue, 10 May 2022 12:05:00 +0000 |
| Subject: | note 127044 added to function.array-is-list | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-218368@lists.php.net to get a copy of this message | ||
slightly optimized version of phpnet at jesseschalken dot com's excellent array_is_list:
<?php
if (!function_exists("array_is_list")) {
function array_is_list(array $array): bool
{
$i = -1;
foreach ($array as $k => $v) {
++$i;
if ($k !== $i) {
return false;
}
}
return true;
}
}
?>
benchmarks: https://3v4l.org/9BPqL
why is this faster you ask? because post-increment does more,
here is what pre-increment actually means:
step 1: increment the value by 1.
step 2: return the value.
here is what post-increment actually means:
step 1: create a copy of the original value.
step 2: increment the original value by 1.
step 3: return the copy.
another question might be "why didn't you write
if ($k !== ++$i) { ? ...
that is a good question! turns out that ++$i;if($k!==$i){...} is faster on PHP7 than if($k !==
++$i){...} for reasons unknown to me.. (if you have an answer, feel free to email me about it!)
(i have NOT checked if PHP8/jit auto-optimize this stuff, but at least back in PHP7 it's true
that pre-increment is faster than post-increment, and this polyfill is primarily for PHP7)
----
Server IP: 45.112.84.4
Probable Submitter: 185.85.3.47 (proxied: 84.49.158.188)
----
Manual Page -- https://php.net/manual/en/function.array-is-list.php
Edit -- https://main.php.net/note/edit/127044
Del: integrated -- https://main.php.net/note/delete/127044/integrated
Del: useless -- https://main.php.net/note/delete/127044/useless
Del: bad code -- https://main.php.net/note/delete/127044/bad+code
Del: spam -- https://main.php.net/note/delete/127044/spam
Del: non-english -- https://main.php.net/note/delete/127044/non-english
Del: in docs -- https://main.php.net/note/delete/127044/in+docs
Del: other reasons-- https://main.php.net/note/delete/127044
Reject -- https://main.php.net/note/reject/127044
Search -- https://main.php.net/manage/user-notes.php