dict和list的性能对比

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012447842/article/details/80115480
#coding=utf-8

import time
import profile


#explain: Cookbook, 5.12  检查序列的成员


def addUnique (baseList , otherList):
    baseDict = dict .fromkeys(baseList)
    for other in otherList:
        if other not in baseDict :
            baseList.append(other)
            baseDict [other] = None


def addUnique_simple (baseList , otherList):
    for other in otherList:
        if other not in baseList:
            baseList.append(other)

if __name__ == '__main__' :
    a = range ( 1 , 100 )
    b = range ( 90 , 110 )

    # start = time.time()

    profile.run( 'addUnique(a, b)' )
    # end = time.time()
    # print 'res:', a
    # print 'b: ', b
    # print 'spend_time', end - start

    a = range ( 1 , 100 )
    b = range ( 90 , 110 )

    # start = time.time()
    profile.run( "addUnique_simple(a, b)" )
    # end = time.time()

    # print 'res:', a
    # print 'b: ', b
    # print 'simple spend_time', end - start

addUnique: 消耗的时间就正比于两个列表的长度之和, 一是dict.fromkeys(baseList) 时间正比于baseList的长度,
二: for循环,正比于otherList的长度。

addUnique_simple: 消耗的时间就正比于两个列表的长度的乘积。 在for循环内嵌套一层otherList的复杂度O(n)。

性能优化:
      Python 字典中使用了 hash table,因此查找操作的复杂度为 O(1),而 list 实际是个数组,在 list 中,查找需要遍历整个 list,其复杂度为 O(n),因此对成员的查找访问等操作字典要比 list 更快。


猜你喜欢

转载自blog.csdn.net/u012447842/article/details/80115480