LSLínguas Sem BenaventeInglês para brasileiros

Aula

Performance code review

Nível: C1

Objetivo

Fazer performance review de código em C1 com foco em hot path, allocation, query plan, concurrency, caching e benchmark validity. O foco é distinguir problema real de otimização prematura, com dado e medição, não opinião.

Explicação

Performance review em C1 não é 'isso está lento'; é 'isso é lento no hot path porque X, e tem benchmark que prova Y'. Seis eixos:

1. Hot path

Onde o código roda frequentemente. C1 sempre pergunta: 'is this in the hot path?' Otimização fora do hot path é ruído; otimização no hot path é engenharia. `This is called 10k times per second, so the allocation matters.`

2. Allocation

Criação de objetos. C1 cita: 'this function allocates a new list on every call' ou 'this dictionary has 1000 keys, so the lookup allocates memory'. Allocation em hot path é fonte clássica de latência em Python/Go/Java.

3. Query plan

Como o banco executa a query. C1 sempre pede EXPLAIN. `The query plan shows a sequential scan on 10M rows; we need an index on (user_id, created_at).` Review sem EXPLAIN é opinião.

4. Concurrency

Race conditions, locks, contention. C1 cita: 'this lock is held during the network call, so it serializes all writes' ou 'this counter is not atomic, so we have a race'. Concurrency C1 sempre cita o efeito, não 'pode ter race'.

5. Caching

Cache hit rate, invalidation, TTL. C1 cita: 'this cache has a 20% hit rate; we are paying the cost without the benefit'. Caching C1 mede antes de recomendar.

6. Benchmark validity

O benchmark prova o que diz? C1 sempre pergunta: 'did the benchmark run on the same data shape? same hardware? warm cache?' Benchmark sem contexto é otimização prematura.

Exemplos

InglêsTraduçãoObservação
This is called 10k times per second, so the allocation matters.Isto é chamado 10 mil vezes por segundo, então a alocação importa.Hot path: frequência importa.
The query plan shows a sequential scan on 10M rows; we need an index on (user_id, created_at).O plano da query mostra um sequential scan em 10 milhões de linhas; precisamos de um índice em (user_id, created_at).Query plan: EXPLAIN mostra o problema.
This lock is held during the network call, so it serializes all writes.Este lock é mantido durante a chamada de rede, então serializa todas as escritas.Concurrency: lock + efeito.
This cache has a 20% hit rate; we are paying the cost without the benefit.Este cache tem taxa de acerto de 20%; estamos pagando o custo sem o benefício.Caching: hit rate baixo é prejuízo.
Did the benchmark run on the same data shape and the same hardware? Without that, the result is not actionable.O benchmark rodou na mesma forma de dados e no mesmo hardware? Sem isso, o resultado não é acionável.Benchmark validity: contexto importa.

Erros comuns

  • Otimizar fora do hot path: 'isso é lento' sem mostrar frequência é ruído.
  • Pedir micro-otimização: 'use list comprehension' é micro-otimização; C1 foca em allocation e query plan.
  • Pedir cache sem medir: cache é trade-off; sem hit rate, é palpite.
  • Não pedir EXPLAIN: query lenta sem EXPLAIN é opinião, não diagnóstico.
  • Aceitar benchmark sem contexto: benchmark sem data shape e hardware não prova nada.

Prática guiada

Reescreva cada crítica de performance abaixo no padrão C1.

  1. Hot path: cite a frequência de chamada.
  2. Allocation: cite o que é alocado e por que importa.
  3. Query plan: cite o EXPLAIN e o índice faltando.
  4. Concurrency: cite o efeito observável (serialização, race).
  5. Caching: cite o hit rate, não 'vamos cachear'.
  6. Benchmark: cite o data shape e o hardware, não só o número.

Resumo

Performance review C1 tem seis eixos: hot path (frequência), allocation (objetos criados), query plan (EXPLAIN), concurrency (lock + efeito), caching (hit rate), benchmark validity (data shape + hardware). Sem dado, é opinião; com EXPLAIN + medição, é engenharia.

Vocabulário

Palavras principais

8 itens
hot pathcódigo que roda com alta frequência

Is this in the hot path?

Isso está no hot path?
allocationcriação de objetos em memória

Allocation in the hot path adds latency.

Alocação no hot path adiciona latência.
query planplano de execução da query no banco

The query plan shows a sequential scan.

O plano da query mostra um sequential scan.
EXPLAINcomando que mostra o plano de execução de uma query

Always run EXPLAIN before recommending an index.

Sempre rode EXPLAIN antes de recomendar um índice.
sequential scanleitura sequencial de todas as linhas de uma tabela

A sequential scan on 10M rows is slow.

Um sequential scan em 10 milhões de linhas é lento.
concurrencyexecução simultânea de código

Concurrency issues manifest under load.

Problemas de concorrência aparecem sob carga.
lock contentiondisputa por um lock entre threads

Lock contention serializes all writes.

Lock contention serializa todas as escritas.
cache hit ratetaxa de acerto do cache

A 20% hit rate means the cache is not paying off.

Uma taxa de acerto de 20% significa que o cache não está compensando.

História

História: Performance code review

Nível: C1

História em inglês

Reviewing a slow checkout query

On Friday, I had to review a slow checkout query that the team flagged as P1. I opened with EXPLAIN: the query plan shows a sequential scan on the orders table (10M rows); the query is in the hot path (called 5k times per second). I added a suggestion: add an index on (customer_id, created_at) and re-run EXPLAIN to confirm the new plan. I questioned a cache: the cache has a 20% hit rate, which means 80% of requests hit the database anyway; the cost is not justified. I closed with the benchmark validity: did the team's benchmark run on the same data shape and hardware as production? Without that, the result is not actionable. The team thanked me for the calibrations: now we know what is a P1 and what is a micro-optimization.

Tradução linha por linha

InglêsTradução
On Friday, I had to review a slow checkout query that the team flagged as P1.Na sexta, eu tive que revisar uma query lenta de checkout que o time marcou como P1.
I opened with EXPLAIN: the query plan shows a sequential scan on the orders table (10M rows); the query is in the hot path (called 5k times per second).Eu abri com EXPLAIN: o plano da query mostra um sequential scan na tabela de pedidos (10 milhões de linhas); a query está no hot path (chamada 5 mil vezes por segundo).
I added a suggestion: add an index on (customer_id, created_at) and re-run EXPLAIN to confirm the new plan.Eu adicionei uma sugestão: adicionar um índice em (customer_id, created_at) e rodar EXPLAIN de novo para confirmar o novo plano.
I questioned a cache: the cache has a 20% hit rate, which means 80% of requests hit the database anyway; the cost is not justified.Eu questionei um cache: o cache tem taxa de acerto de 20%, o que significa que 80% das requisições vão ao banco; o custo não se justifica.
I closed with the benchmark validity: did the team's benchmark run on the same data shape and hardware as production? Without that, the result is not actionable.Eu fechei com a validade do benchmark: o benchmark do time rodou na mesma forma de dados e hardware que a produção? Sem isso, o resultado não é acionável.
The team thanked me for the calibrations: now we know what is a P1 and what is a micro-optimization.O time agradeceu pelas calibrações: agora sabemos o que é P1 e o que é micro-otimização.

Notas de vocabulário

  • query plan shows a sequential scan on 10M rows = EXPLAIN: dado, não opinião.
  • called 5k times per second = hot path: frequência importa.
  • cache has a 20% hit rate = caching com hit rate.
  • did the benchmark run on the same data shape = benchmark validity: contexto importa.
  • now we know what is a P1 and what is a micro-optimization = maturidade C1: calibrar severidade.

Perguntas de compreensão

  1. O que diferencia performance review C1 de opinião?
  2. O que torna uma crítica de query plan C1 útil?
  3. Quando recomendar cache em C1?

Prática com a história

  1. Escreva uma crítica de performance C1 para uma query lenta.
  2. Escreva uma crítica de caching C1 com hit rate.
  3. Escreva uma crítica de benchmark validity C1.

Prática

Exercícios e teste

Próxima etapa
3blocos de exercícios disponíveis neste tema
10questões de teste para revisar depois da aula

A próxima melhoria é transformar esses arquivos em perguntas com resposta no navegador. Por enquanto, esta página já organiza o estudo e permite seguir a aula inteira sem abrir os arquivos manualmente.