Question

I am in doubt what to use:

foreach(){
    // .....

    if(!in_array($view, $this->_views[$condition]))
        array_push($this->_views[$condition], $view);

    // ....
}

OR

foreach(){
    // .....

    array_push($this->_views[$condition], $view);

    // ....
}

$this->_views[$condition] = array_unique($this->_views[$condition]);

UPDATE

The goal is to get array of unique values. This can be done by checking every time if value already exists with in_array or add all values each time and in the end use array_unique. So is there any major difference between this two ways?

Was it helpful?

Solution

I think the second approach would be more efficient. In fact, array_unique sorts the array then scans it.

Sorting is done in N log N steps, then scanning takes N steps.

The first approach takes N^2 steps (foreach element scans all N previous elements). On big arrays, there is a very big difference.

OTHER TIPS

Honestly if you're using a small dataset it does not matter which one you use. If your dataset is in the 10000s you'll most definitely want to use a hash map for this sort of thing.

This is assuming the views are a string or something, which it looks like it is. This is typically O(n) and possibly the fastest way to deal with tracking unique values.

foreach($views as $view)
{
    if(!array_key_exists($view,$unique_views))
    {
        $unique_views[$condition][$view] = true;
    }
}

TL;DR: foreach combined with if (!in_array()) is better.

Truthfully you should not really worry about what performs better; in most cases the difference is so small, its negligible (unless you're really doing some big data stuff). I would suggest to go with whatever seems more readable.

If you're interested, check out this script I wrote. It loops each case 100.000 times and both take between 50 and 200 ms.

https://3v4l.org/lkTCF

Note that array_unique() keeps the original keys so to counter that we also have to wrap the result with array_values().

In case the link ever dies:

<?php
$loops = 100000;

$start = microtime(true);
for ($l = 0; $l < $loops; $l++) {
    $x = [1,2,3,4,6,7,8,9];
    for ($i = 0; $i <= 10; $i++) {
        if (!in_array($i, $x)) {
            $x[] = $i;
        }
    }
}
$duration = microtime(true) - $start;
echo "in_array took $duration<br>".PHP_EOL;

$start = microtime(true);
for ($l = 0; $l < $loops; $l++) {
    $x = [1,2,3,4,6,7,8,9];
    $x = array_values(array_unique(array_merge($x, [0,1,2,3,4,5,6,7,8,9,10])));
}
$duration = microtime(true) - $start;
echo "array_unique took $duration<br>".PHP_EOL;

enter image description here enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top