Quick actions

cmd+k|ctrl+k

Navigation

Languages

Benchmark: array_search vs array_find

Snippet info

Language

Php

Visibility

public

Author

legacy-v1-2589

Created

2019-04-26T11:52:17Z

Updated

2019-04-26T11:52:17Z

<?php

function array_find($key, $needle, $haystack) {
    return array_column($haystack, null, $key)[$needle];
}

function array_find_search($key, $needle, $haystack) {
    $key = array_search($needle, array_column($haystack, $key, null));
    return $haystack[$key];
}

function array_find_filter($key, $needle, $haystack) {
    $value = array_filter($haystack, function($field) use ($key, $needle) {
        return $field->$key === $needle;
    });
    
    return reset($value);
}

function runTests($debug = false) {
    return [
        'array_filter' => test_array_filter($debug),
        'array_search' => test_array_search($debug),
        'array_find' => test_array_find($debug),
    ];
}


function test_array_filter($debug) {
    $fields = array_map(function($val) {
        return (object) ['nid' => "field_$val", 'position' => $val];
    }, range(1, 5000));
    
    $start_time = microtime(TRUE);
    $value = array_find_filter('nid', 'field_3000', $fields);
    $end_time = microtime(TRUE);
    
    if ($debug) {
        echo __FUNCTION__ . ": ";
        print_r($value);
        
    }
    
    return $end_time - $start_time;
}

function test_array_search($debug) {
    $fields = array_map(function($val) {
        return (object) ['nid' => "field_$val", 'position' => $val];
    }, range(1, 5000));
    
    
    $start_time = microtime(TRUE);
    $value = array_find_search('nid', 'field_3000', $fields);
    $end_time = microtime(TRUE);
    
    if ($debug) {
        echo __FUNCTION__ . ": ";
        print_r($value);
        
    }
    
    return $end_time - $start_time;
}

function test_array_find($debug) {
    $fields = array_map(function($val) {
        return (object) ['nid' => "field_$val", 'position' => $val];
    }, range(1, 5000));
    
    $start_time = microtime(TRUE);
    $value = array_find('nid', 'field_3000', $fields);
    $end_time = microtime(TRUE);
    
    if ($debug) {
        echo __FUNCTION__ . ": ";
        print_r($value);
        
    }
    
    return $end_time - $start_time;
}

$results = [];

for ($i = 1; $i <= 1000; $i++) {
    $results[] = runTests();
}

$benchResult = [
    'array_find' => array_sum(array_column($results, 'array_find')),
    'array_filter' => array_sum(array_column($results, 'array_filter')),
    'array_search' => array_sum(array_column($results, 'array_search')),
];

asort($benchResult);

print_r($benchResult);
echo "==============================================\n";

runTests(true);




INFO