什么是更好的使用:in_array或array_unique?

时间:2021-11-22 20:22:28

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

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?

目标是获得一系列独特的价值观。这可以通过每次检查in_array中是否已存在值或每次添加所有值并最终使用array_unique来完成。那么这两种方式之间有什么重大区别吗?

2 个解决方案

#1


7  

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

我认为第二种方法会更有效率。实际上,array_unique对数组进行排序然后扫描它。

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

排序以N log N步骤完成,然后扫描需要N步。

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

第一种方法需要N ^ 2步(foreach元素扫描所有N个前面的元素)。在大阵列上,存在很大的差异。

#2


2  

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.

老实说,如果你使用的是小型数据集,那么使用哪一个并不重要。如果您的数据集在10000s内,那么您肯定希望使用哈希映射来处理这类事情。

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.

这假设视图是一个字符串或其他东西,它看起来像它。这通常是O(n),可能是处理跟踪唯一值的最快方法。

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

#1


7  

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

我认为第二种方法会更有效率。实际上,array_unique对数组进行排序然后扫描它。

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

排序以N log N步骤完成,然后扫描需要N步。

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

第一种方法需要N ^ 2步(foreach元素扫描所有N个前面的元素)。在大阵列上,存在很大的差异。

#2


2  

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.

老实说,如果你使用的是小型数据集,那么使用哪一个并不重要。如果您的数据集在10000s内,那么您肯定希望使用哈希映射来处理这类事情。

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.

这假设视图是一个字符串或其他东西,它看起来像它。这通常是O(n),可能是处理跟踪唯一值的最快方法。

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