แม้ Python จะไม่เร็วเท่าภาษา compiled อื่นๆ แต่บริษัทใหญ่หลายแห่งพิสูจน์ว่า Python จัดการ workload ใหญ่ได้ดี ในบทความนี้จะนำเสนอ 11 เทคนิคเพื่อให้โค้ด Python ทำงานเร็วขึ้นและมีประสิทธิภาพมากขึ้น
เคล็ดลับที่ 1: ใช้ Built-in Functions
Built-in functions เขียนด้วย C ทำให้เร็วกว่าการเขียนเองมาก ใช้ len(), sum(), max(), min(), sorted() แทนการเขียนลูปเอง
เคล็ดลับที่ 2: ใช้ Multiple Assignment สำหรับสลับค่า
# ช้า - ใช้ตัวแปรชั่วคราว temp = x x = y y = temp # เร็ว - Python multiple assignment x, y = y, x
เคล็ดลับที่ 3: หลีกเลี่ยง Global Variables
Python เข้าถึง local variables เร็วกว่า global variables มาก ควรใช้ local variables ในฟังก์ชันให้มากที่สุด
เคล็ดลับที่ 4: ใช้คีย์เวิร์ด "in" สำหรับตรวจสอบสมาชิก
# ใช้ in - เร็วและอ่านง่าย
for key in sequence:
print("Hello", key)
# หลีกเลี่ยงการใช้ index หรือ range(len())
เคล็ดลับที่ 5: ใช้ "while 1" สำหรับ Infinite Loop
# เร็วกว่าเล็กน้อย (single jump operation)
while 1:
# do something
# ช้ากว่า
while True:
# do something
เคล็ดลับที่ 6: ใช้ List Comprehension
List comprehension เร็วกว่าลูป for/while ธรรมดา เพราะ interpreter optimize ได้ดีกว่า
# ดี - List comprehension
evens = [i for i in range(25) if i % 2 == 0]
# ไม่ค่อยดี - while loop
i = 0
evens = []
while i < 25:
if i % 2 == 0:
evens.append(i)
i += 1
เคล็ดลับที่ 7: ใช้ Generators สำหรับค่าแบบ On-Demand
Generators ประหยัดหน่วยความจำ เพราะสร้างค่าทีละอันเมื่อต้องการ (lazy evaluation)
# Generator expression chunk_bytes = (1000 * i for i in range(1000)) next(chunk_bytes) # 0 next(chunk_bytes) # 1000 next(chunk_bytes) # 2000
เคล็ดลับที่ 8: ใช้โมดูล itertools
itertools มีฟังก์ชันสำหรับ iteration และ combination ที่มีประสิทธิภาพสูง
import itertools list(itertools.permutations([1, 2, 3, 4])) # สร้าง permutations ทั้งหมด 24 แบบ
เคล็ดลับที่ 9: ใช้โมดูล bisect สำหรับรายการที่เรียงลำดับ
bisect.insort() ทำ binary search และ insert พร้อมกัน รักษาลำดับการเรียงได้โดยไม่ต้อง sort() ใหม่
import bisect bisect.insort(sorted_list, new_element)
เคล็ดลับที่ 10: ใช้ Dictionary และ Set สำหรับ Membership Test
Dictionary และ Set ใช้ hash table → lookup O(1) เร็วกว่ารายการ (list) ที่เป็น O(n)
lst = ['a', 'ab', 'abc'] # ช้า O(n)
'abc' in lst
my_set = {'a', 'ab', 'abc'} # เร็ว O(1)
'abc' in my_set
เคล็ดลับที่ 11: Cache ผลลัพธ์ด้วย Decorator (Memoization)
ใช้ functools.lru_cache หรือสร้าง decorator เองเพื่อจดจำผลลัพธ์
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return 1
return fib(n-1) + fib(n-2)
# เรียก fib(100) เร็วมาก เพราะ cache ผลลัพธ์ไว้
สรุป
การนำเทคนิคเหล่านี้ไปใช้จะช่วยให้โค้ด Python ของคุณทำงานเร็วขึ้น ลดการใช้หน่วยความจำ และอ่านง่ายขึ้น