Code snippets
Code snippets
Copy-ready answers to everyday coding questions, each with a short explanation. Laravel, PHP, JavaScript, SQL, Bash and more.
8 snippets tagged #performance · Show all
PHP
November 2, 2026
Laravel chunkById and lazy: process large tables without running out of memory
Loads rows in batches instead of all at once, so big tables don’t exhaust memory. Prefer chunkById when you update rows while looping.
<?php
User::chunkById(1000, function ($users) {
foreach ($users as $user) {
SQL
October 20, 2026
MySQL add an index and check it with EXPLAIN
Adds an index to speed up a slow WHERE clause, then uses EXPLAIN to confirm the query uses it. Check that key is set and rows is small.
ALTER TABLE orders ADD INDEX idx_user_created (user_id, created_at);
EXPLAIN
SELECT * FROM orders
PHP
October 19, 2026
Laravel queue job to run slow tasks in the background
Moves slow work such as sending email or processing files out of the web request so pages respond fast. Run a worker with php artisan queue:work.
<?php
// php artisan make:job SendWelcomeEmail
namespace App\Jobs;
JavaScript
October 14, 2026
JavaScript debounce function to limit how often a function runs
Delays a function until the user stops triggering it for a set time. Use it for search boxes, window resize and autosave so you don’t fire on every keystroke.
function debounce(fn, delay = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
PHP
October 10, 2026
Laravel Cache::flexible stale-while-revalidate caching
Serves the cached value instantly, even after it goes stale, and refreshes it in the background after the response is sent. Use it for slow queries on busy page...
<?php
use Illuminate\Support\Facades\Cache;
PHP
October 10, 2026
Laravel Concurrency::run execute tasks in parallel
Runs several closures at the same time and returns their results in order. Use it when a page needs independent slow calls, such as two reports or two APIs, and...
<?php
use Illuminate\Support\Facades\Concurrency;
PHP
October 8, 2026
Laravel cache expensive query with Cache::remember
Runs the query once and serves the result from cache for the given time. Use it for heavy queries on pages with lots of traffic, and forget the key when the dat...
<?php
use Illuminate\Support\Facades\Cache;
PHP
October 3, 2026
Laravel Eager Loading with Eloquent: Avoid N+1 Queries
Laravel Eloquent eager loading lets you load model relationships in advance using the with() method, helping prevent the N+1 query problem and reducing unnecess...
use App\Models\Post;
// Eager load the author and comments relationships
$posts = Post::with(['author', 'comments'])->get();