Laravel의 코드 최적화 및 성능 개선을 위한 팁

WBOY
풀어 주다: 2024-09-12 16:19:02
원래의
483명이 탐색했습니다.

Tips for Code Optimization and Performance Improvement in Laravel

Laravel은 강력하고 우아한 프레임워크이지만 애플리케이션이 성장함에 따라 성능 최적화가 필수적입니다. 다음은 성능을 향상하고 Laravel 애플리케이션을 최적화하는 데 도움이 되는 팁과 예제가 포함된 포괄적인 가이드입니다.

1. Eager 로딩과 Lazy 로딩

문제: 기본적으로 Laravel은 지연 로딩을 사용하므로 여러 데이터베이스 쿼리가 불필요하게 실행되는 "N+1 쿼리 문제"가 발생할 수 있습니다.

최적화: eager loading을 사용하여 하나의 쿼리로 관련 데이터를 로드하면 관계 작업 시 성능이 크게 향상됩니다.

이전(지연 로딩):

// This runs multiple queries (N+1 Problem)
$users = User::all();

foreach ($users as $user) {
    $posts = $user->posts;
}
로그인 후 복사

이후(즉시 로딩):

// This loads users and their posts in just two queries
$users = User::with('posts')->get();
로그인 후 복사

핵심 사항: 관련 모델이 필요할 것이라는 점을 알면 항상 즉시 로딩을 사용하세요.


2. 비용이 많이 드는 쿼리에 캐싱 사용

문제: 동일한 데이터(예: 사용자 목록, 설정, 제품 카탈로그)를 자주 가져오면 성능 병목 현상이 발생할 수 있습니다.

최적화: 비용이 많이 드는 쿼리 및 계산 결과를 캐시하여 로드 시간과 데이터베이스 쿼리를 줄입니다.

이전(캐싱 없음):

// Querying the database every time
$users = User::all();
로그인 후 복사

이후(캐시 사용):

// Caching the user data for 60 minutes
$users = Cache::remember('users', 60, function () {
    return User::all();
});
로그인 후 복사

핵심 사항: Laravel의 캐싱 시스템(Redis, Memcached)을 사용하여 불필요한 데이터베이스 쿼리를 줄이세요.


3. 데이터베이스 쿼리 최적화

문제: 비효율적인 쿼리와 적절한 색인 생성이 부족하면 성능이 크게 저하될 수 있습니다.

최적화: 자주 쿼리되는 열에는 항상 인덱스를 추가하고, 필요한 데이터만 사용하세요.

전에:

// Fetching all columns (bad practice)
$orders = Order::all();
로그인 후 복사

후에:

// Only fetching necessary columns and applying conditions
$orders = Order::select('id', 'status', 'created_at')
    ->where('status', 'shipped')
    ->get();
로그인 후 복사

주요 사항: 항상 필요한 열을 지정하고 데이터베이스가 자주 쿼리되는 필드에 대해 적절한 색인을 생성하는지 확인하세요.


4. 미들웨어 사용 최소화

문제: 미들웨어를 모든 경로에 전체적으로 적용하면 불필요한 오버헤드가 추가될 수 있습니다.

최적화: 필요한 부분에만 미들웨어를 선택적으로 적용합니다.

이전(글로벌 미들웨어 사용):

// Applying middleware to all routes
Route::middleware('logRouteAccess')->group(function () {
    Route::get('/profile', 'UserProfileController@show');
    Route::get('/settings', 'UserSettingsController@index');
});
로그인 후 복사

이후(선택적 미들웨어 사용):

// Apply middleware only to specific routes
Route::get('/profile', 'UserProfileController@show')->middleware('logRouteAccess');
로그인 후 복사

주요 사항: 미들웨어는 성능 저하를 방지하기 위해 필요한 경우에만 적용해야 합니다.


5. 대규모 데이터 세트에 대한 페이지 매김 최적화

문제: 대용량 데이터 세트를 한 번에 가져와서 표시하면 메모리 사용량이 많아지고 응답 속도가 느려질 수 있습니다.

최적화: 페이지 매김을 사용하여 요청당 가져오는 레코드 수를 제한하세요.

이전(모든 기록 가져오기):

// Fetching all users (potentially too much data)
$users = User::all();
로그인 후 복사

이후(페이지 매김 사용):

// Fetching users in chunks of 10 records per page
$users = User::paginate(10);
로그인 후 복사

주요 사항: 대규모 데이터세트를 페이지로 나누어 데이터베이스의 부담을 피하고 메모리 사용량을 줄이세요.


6. 장기 실행 작업 대기열에 넣기

문제: 이메일 보내기, 보고서 생성 등 장기 실행 작업으로 인해 요청 응답 시간이 느려집니다.

최적화: 대기열을 사용하여 작업을 오프로드하고 백그라운드에서 비동기식으로 처리합니다.

이전(동기 작업):

// Sending email directly (slows down response)
Mail::to($user->email)->send(new OrderShipped($order));
로그인 후 복사

이후(대기 중인 작업):

// Queuing the email for background processing
Mail::to($user->email)->queue(new OrderShipped($order));
로그인 후 복사

핵심 사항: 시간에 민감하지 않은 작업에 대기열을 사용하여 응답 시간을 개선하세요.


7. 라우팅, 구성 및 보기 캐싱 사용

문제: 경로, 구성 또는 보기를 캐싱하지 않으면 특히 프로덕션 환경에서 성능이 저하될 수 있습니다.

최적화: 프로덕션 성능 향상을 위해 경로, 구성 파일 및 뷰를 캐시합니다.

예제 명령:

# Cache routes
php artisan route:cache

# Cache configuration files
php artisan config:cache

# Cache compiled views
php artisan view:cache
로그인 후 복사

주요 사항: 더 빠른 애플리케이션 성능을 위해 프로덕션 환경에서 항상 구성, 경로 및 보기를 캐시하세요.


8. 코드를 정리하려면 Compact()를 사용하세요.

문제: 여러 변수를 뷰에 수동으로 전달하면 코드가 장황하고 관리하기 어려울 수 있습니다.

최적화: compact()를 사용하여 여러 변수를 뷰에 전달하는 프로세스를 단순화합니다.

전에:

return view('profile', [
    'user' => $user,
    'posts' => $posts,
    'comments' => $comments,
]);
로그인 후 복사

후에:

return view('profile', compact('user', 'posts', 'comments'));
로그인 후 복사

핵심 사항: Compact()를 사용하면 코드가 더 간결해지고 유지 관리가 쉬워집니다.


9. Use Redis or Memcached for Session and Cache Storage

Problem: Storing sessions and cache data in the file system slows down your application in high-traffic environments.

Optimization: Use fast in-memory storage solutions like Redis or Memcached for better performance.

Example Config for Redis:

// In config/cache.php
'default' => env('CACHE_DRIVER', 'redis'),

// In config/session.php
'driver' => env('SESSION_DRIVER', 'redis'),
로그인 후 복사

Key Takeaway: Avoid using the file driver for sessions and caching in production, especially in high-traffic applications.


10. Avoid Using Raw Queries Unless Necessary

Problem: Using raw SQL queries can make your code less readable and harder to maintain.

Optimization: Use Laravel’s Eloquent ORM or Query Builder whenever possible, but if raw queries are necessary, ensure they are optimized.

Before (Raw Query):

// Using raw query directly
$users = DB::select('SELECT * FROM users WHERE status = ?', ['active']);
로그인 후 복사

After (Using Eloquent or Query Builder):

// Using Eloquent ORM for better readability and maintainability
$users = User::where('status', 'active')->get();
로그인 후 복사

Key Takeaway: Prefer Eloquent ORM over raw queries unless absolutely necessary.


11. Use Efficient Logging Levels

Problem: Logging everything at all times can cause performance degradation and fill up your storage.

Optimization: Set proper log levels in production to capture only what’s necessary (e.g., errors and critical messages).

Example:

// In .env file, set log level to 'error' in production
LOG_LEVEL=error
로그인 후 복사

Key Takeaway: Log only what’s necessary in production to avoid unnecessary storage usage and performance hits.


Final Thoughts

Optimizing Laravel performance is crucial for scalable and efficient applications. By implementing these best practices, you can ensure that your Laravel app runs faster, handles more traffic, and offers a better user experience.

Let me know what you think, or feel free to share your own tips and tricks for optimizing Laravel applications!

Happy coding! ?

위 내용은 Laravel의 코드 최적화 및 성능 개선을 위한 팁의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!