python list 的+、+=和extend操作

据说后者在list很大的时候性能稍好。

于是测试了一把:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import time
 
def time_cost(func):
    def _time_cost(*args,**kw):
        t1=time.time()
        func(*args,**kw)
        t2=time.time()
        return t2-t1
    return _time_cost
 
@time_cost
def test_add(list_a,huge_list_b):
    return list_a+huge_list_b
@time_cost
def test_extend(list_a,huge_list_b):
    return list_a.extend(huge_list_b)
 
 
if __name__=='__main__':
    print '-----big list test-------------'
    a=[1]*1000
    b=['a']*(10**8)
    print 'add cost:%s seconds'%test_add(a,b)
    print 'extend cost:%s seconds'%test_extend(a,b)
 
    print '-----small list test-------------'
    a=[1]*1000
    b=['a']*(10**2)
    print 'add cost:%s seconds'%test_add(a,b)
    print 'extend cost:%s seconds'%test_extend(a,b)

  

  

我机器是win7,64bit,6G 内存,i3 cpu,结果如下:

1
2
3
4
5
6
-----big list test-------------
add cost:1.30500006676 seconds
extend cost:0.591000080109 seconds
-----small list test-------------
add cost:0.0 seconds
extend cost:0.0 seconds

  

在b为10^8长度的时候,extend所耗的时间几乎只有+操作的一半。

在1000长度的级别,相差不大。几乎相同。

 

+=等同于extend,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import time
 
def time_cost(func):
    def _time_cost(*args,**kw):
        t1=time.time()
        func(*args,**kw)
        t2=time.time()
        return t2-t1
    return _time_cost
 
@time_cost
def test_add(list_a,huge_list_b):
    list_a+=huge_list_b
    return list_a
@time_cost
def test_extend(list_a,huge_list_b):
    return list_a.extend(huge_list_b)
 
 
if __name__=='__main__':
    print '-----big list test-------------'
    a=[1]*1000
    b=['a']*(10**8)
    a2=[1]*1000
    print '+= cost:%s seconds'%test_add(a,b)
    print 'extend cost:%s seconds'%test_extend(a2,b)

 输出:

1
2
3
-----big list test-------------
+= cost:0.506999969482 seconds
extend cost:0.510999917984 seconds

  

posted @   tommy.yu  阅读(1122)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示