Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
最佳化
|
551
eval
作用於運算式(expressions)上,而非述句(statements),因此,雖
然仍然很慢,它避開了
exec
所帶來的一些最糟的效能衝擊。
eval
也是一
樣,我們建議你最好使用明確的
dict
。如果你需要多次估算(evaluate)動
態取得的同一個字串,就用
compile
編譯一次那個字串,然後對所產生的
程式碼物件重複使用
eval
。甚至更好的是,完全避免
eval
有關
exec
eval
compile
的更多細節和建議,請參閱前面的「動態執行
exec」。
最佳化迴圈
你程式的大多數瓶頸都會在迴圈中,特別是巢狀迴圈(nested loops),
因為迴圈主體會重複地執行。Python 不會隱含地進行任何的
程式碼拉升
code hoisting
:如果你的迴圈中有任何的程式碼可以被拉升到迴圈外
面,變得只執行一次,而且那個迴圈是個瓶頸,那你就自行拉升那些程式
碼。有的時候,可以拉升的程式碼並不是那麼明顯:
def slower(anobject, ahugenumber):
for i in range(ahugenumber): anobject.amethod(i)
def faster(anobject, ahugenumber):
themethod = anobject.amethod
for i in range(ahugenumber): themethod(i)
在這種情況中,
faster
拉到迴圈外的程式碼是
anobject.amethod
這個屬
性查找
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819