---
title: Ưu tiên dùng .min() hoặc .max() thay vì sorted().first/last
impact: CRITICAL
impactDescription: Tăng hiệu năng đáng kể (O(n) so với O(n log n)) khi tìm phần tử lớn nhất/nhỏ nhất trong collection.
tags: swift, ios, performance, algorithms, collection
---

## Ưu tiên dùng .min() hoặc .max() thay vì sorted().first/last

Sử dụng `.min()` hoặc `.max()` thay vì `.sorted().first` hoặc `.sorted().last`. Việc gọi `sorted()` sẽ phải sắp xếp toàn bộ tập hợp (độ phức tạp O(n log n)), trong khi `.min()`/`.max()` chỉ duyệt qua tập hợp đúng 1 lần (độ phức tạp O(n)). Điều này giúp tăng hiệu năng rõ rệt trên các tập dữ liệu lớn.

**Incorrect (sort rồi lấy phần tử đầu/cuối):**

```swift
let numbers = [5, 3, 8, 1, 9]
let minNumber = numbers.sorted().first
let maxNumber = numbers.sorted().last
```

**Correct (dùng hàm chuyên dụng):**

```swift
let numbers = [5, 3, 8, 1, 9]
let minNumber = numbers.min()
let maxNumber = numbers.max()
```

**Tools:** SwiftLint (sorted_first_last)
