javascript
star
bookmark_border
Run a function only after the user stops typing or resizing.
function debounce(fn, wait = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
beginner
#performance #events #functions
python
bookmark_border
Memoize a pure function with functools.lru_cache.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n: int) -> int:
beginner
#performance #functools #recursion
javascript
bookmark_border
One listener on a parent handles clicks for current and future children.
document.body.innerHTML = `
<ul id="todo">
<li>Write tests <button data-action="done">Done</button></li>
<li>Deploy <button data-action="done">Done</button></li>
</ul>`;
intermediate
#dom #events #performance
sql
bookmark_border
The queries using the most total time (needs the pg_stat_statements extension).
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT round(total_exec_time::numeric, 1) AS total_ms,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
advanced
#postgres #performance #monitoring
sql
bookmark_border
Page through big tables without the slowdown of large OFFSET values.
-- first page
SELECT id, title, created_at FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20;
intermediate
#pagination #performance
html
bookmark_border
Serve the right size and format, and avoid layout shift.
<picture>
<source type="image/webp"
srcset="/img/hero-640.webp 640w, /img/hero-1280.webp 1280w, /img/hero-1920.webp 1920w"
sizes="(max-width: 700px) 100vw, 1200px">
<img src="/img/hero-1280.jpg"
beginner
#images #performance
javascript
bookmark_border
Process many async jobs, but only N at a time.
async function mapLimit(items, limit, worker) {
const results = new Array(items.length);
let next = 0;
async function lane() {
while (next < items.length) {
advanced
#async #promises #performance
python
bookmark_border
A tiny context manager that prints how long a block took.
import time
from contextlib import contextmanager
@contextmanager
intermediate
#performance #context-manager