参见英文答案 > What is the python “with” statement designed for? 10个
我知道有很多关于在python中读取文件的文章和问题.但我仍然想知道是什么让python有多种方法来完成同样的任务.我想知道的是,使用这两种方法对性能有何影响?
解决方法:
使用with语句不是为了获得性能,我认为使用with语句不会产生任何性能上的提升或损失,只要您执行与使用with语句自动执行相同的清理活动.
当你使用带有open函数的语句时,你不需要在最后关闭文件,因为with会自动为你关闭它.
此外,with语句不仅适用于打开文件,还与上下文管理器结合使用.基本上,如果您有一个对象要确保在完成它之后清除它或发生某种错误,您可以将其定义为context manager并且with语句将调用其__enter __()和__exit __()方法在进入和退出with块时.根据PEP 0343 –
This PEP adds a new statement “with” to the Python language to make it possible to factor out standard uses of try/finally statements.
In this PEP, context managers provide __enter__() and __exit__() methods that are invoked on entry to and exit from the body of the with statement.
此外,使用和不使用它的性能测试 –
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 loop
标签:python,performance,file-io
来源: https://codeday.me/bug/20190919/1811999.html