dict和list的性能对比

#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 更快。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

千里风雪

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值