php 數組元素快速去重

來源:互聯網
上載者:User

1.使用array_unique方法進行去重

對數組元素進行去重,我們一般會使用array_unique方法,使用這個方法可以把數組中的元素去重。

123456

輸出:

Array(    [0] => 1    [1] => 2    [2] => 3    [3] => 4    [4] => 5    [5] => 6    [6] => 7    [7] => 8    [8] => 9)123456789101112

去重後,索引值會不按順序,可以使用array_values把索引值重新排序。



2.使用array_unique方法去重效率

';echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms
';echo 'use memory:'.getUseMemory();/** * 擷取使用記憶體 * @return float */function getUseMemory(){ $use_memory = round(memory_get_usage(true)/1024,2).'kb'; return $use_memory;}/** * 擷取microtime * @return float */function getMicrotime(){ list($usec, $sec) = explode(' ', microtime()); return (float)$usec + (float)$sec;}?>1234567891011121314151617181920212223242526272829303132333435363738394041

unique count:99
run time:653.39303016663ms
use memory:5120kb

使用array_unique方法去重,已耗用時間需要約650ms,記憶體佔用約5m



3.更快的數組去重方法

php有一個索引值互換的方法array_flip,我們可以使用這個方法去重,因為索引值互換,原來重複的值會變為相同的鍵。
然後再進行一次索引值互換,把鍵和值換回來則可以完成去重。

';echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms
';echo 'use memory:'.getUseMemory();/** * 擷取使用記憶體 * @return float */function getUseMemory(){ $use_memory = round(memory_get_usage(true)/1024,2).'kb'; return $use_memory;}/** * 擷取microtime * @return float */function getMicrotime(){ list($usec, $sec) = explode(' ', microtime()); return (float)$usec + (float)$sec;}?>123456789101112131415161718192021222324252627282930313233343536373839404142

unique count:99
run time:12.840032577515ms
use memory:768kb

使用array_flip方法去重,已耗用時間需要約18ms,記憶體佔用約2m

因此使用array_flip方法去重比使用array_unique方法已耗用時間減少98%,記憶體佔用減少4/5;

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.