我知道有很多关于阅读python文件的文章和问题得到了解答。但是我仍然想知道是什么让python有多种方式来完成相同的任务。简单地说,我想知道的是,使用这两种方法对性能有什么影响?
发布于 2015-07-10 14:47:49
使用with语句不是为了性能提升,我不认为使用with语句会带来任何性能提升或损失,只要您执行的清理活动与使用with语句自动执行的清理活动相同即可。
当你使用带有open函数的with语句时,你不需要在最后关闭文件,因为with会自动为你关闭它。
此外,with语句不仅用于打开文件,还与上下文管理器结合使用。基本上,如果您有一个对象,您希望确保它在使用完毕或发生某种错误后被清除,则可以将其定义为context manager,并且with语句将在进入和退出with块时调用其__enter__()和__exit__()方法。根据PEP 0343的说法-
这个PEP在Python语言中添加了一个新的语句"
with“,这样就可以排除try/finally语句的标准用法。
在这个PEP中,上下文管理器提供了__enter__()和__exit__()方法,这些方法在进入和退出with语句体时被调用。
另外,使用和不使用with的性能测试-
In [14]: def foo():
....: f = open('a.txt','r')
....: for l in f:
....: pass
....: f.close()
....:
In [15]: def foo1():
....: with open('a.txt','r') as f:
....: for l in f:
....: pass
....:
In [17]: %timeit foo()
The slowest run took 41.91 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 186 µs per loop
In [18]: %timeit foo1()
The slowest run took 206.14 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 179 µs per loop
In [19]: %timeit foo()
The slowest run took 202.51 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 180 µs per loop
In [20]: %timeit foo1()
10000 loops, best of 3: 193 µs per loop
In [21]: %timeit foo1()
10000 loops, best of 3: 194 µs per loophttps://stackoverflow.com/questions/31334061
复制相似问题