Tuesday, 28 August 2018

PHP performance on the check if all elements of the array are of the same type


I've stumbled on what would be the fastest way to check whether or not all elements in an array are of the same type, in PHP. After browsing StackOverflow for different methods to do this, I decided to check which of them is faster. I've tested different approaches (see my self answer below).


Hope this helps.
EDIT
After reading about what "micro-optimization" is, it seems that this is a micro-optimization question. I hadn't heard about this word before 'cause, to my surprise, I always code in a "micro-optimized" way as long as good code readability is kept. Perhaps my roots in data processing programming in the embedded world have turned my mind to some sort of code micro-optimizer :D

$v = range(1, 100000);
$v[]=false; //Put a non-integer element at the end
$testf = 'is_int';
$result = array_reduce (
    $v,
    function($return, $value) use ($testf) {
        return $return && $testf($value);
    },
    true
);

var_dump($result);

EDIT
Results on my laptop:
PHP 5.4.7
TEST isArrayOf_1: result = fail, t = 0.033294200897217
TEST isArrayOf_2: result = fail, t = 0.10196995735168
TEST isArrayOf_3: result = fail, t = 0.052531957626343
TEST isArrayOf_4: result = fail, t = 0.079360961914062

TEST isArrayOf_1: result = fail, t = 0.0085389614105225
TEST isArrayOf_2: result = fail, t = 0.0083901882171631
TEST isArrayOf_3: result = fail, t = 0.044848918914795
TEST isArrayOf_4: result = fail, t = 0.035619020462036

PHP 5.4.21
TEST isArrayOf_1: result = fail, t = 0.032476902008057
TEST isArrayOf_2: result = fail, t = 0.098520040512085
TEST isArrayOf_3: result = fail, t = 0.052137136459351
TEST isArrayOf_4: result = fail, t = 0.074975967407227

TEST isArrayOf_1: result = fail, t = 0.0085029602050781
TEST isArrayOf_2: result = fail, t = 0.0084490776062012
TEST isArrayOf_3: result = fail, t = 0.044224977493286
TEST isArrayOf_4: result = fail, t = 0.035413026809692

PHP 5.3.27
TEST isArrayOf_1: result = fail, t = 0.036087036132812
TEST isArrayOf_2: result = fail, t = 0.11226201057434
TEST isArrayOf_3: result = fail, t = 0.053704977035522
TEST isArrayOf_4: result = fail, t = 0.078150987625122

TEST isArrayOf_1: result = fail, t = 0.0088350772857666
TEST isArrayOf_2: result = fail, t = 0.008991003036499
TEST isArrayOf_3: result = fail, t = 0.045068979263306
TEST isArrayOf_4: result = fail, t = 0.039391994476318

PHP 5.5.5
TEST isArrayOf_1: result = fail, t = 0.029086112976074
TEST isArrayOf_2: result = fail, t = 0.057933807373047
TEST isArrayOf_3: result = fail, t = 0.03432297706604
TEST isArrayOf_4: result = fail, t = 0.052994012832642

TEST isArrayOf_1: result = fail, t = 0.0085070133209229
TEST isArrayOf_2: result = fail, t = 0.0085380077362061
TEST isArrayOf_3: result = fail, t = 0.024166107177734
TEST isArrayOf_4: result = fail, t = 0.034998178482056

0 comments:

Post a Comment