PHP 7: Maintaining and Upgrading Legacy Apps · Performance on PHP 7

Profiling Slow Legacy Pages

Find where time goes with profilers and query logs.

Slow legacy pages are usually slow because of database access: N+1 queries in loops, missing indexes, or loading whole tables. Profile with Xdebug (cachegrind output viewed in KCachegrind/Webgrind), SPX or Blackfire, enable the MySQL slow query log, and count queries per request. Fix the top offenders first and measure again.

; Enable Xdebug profiling only when triggered (?XDEBUG_TRIGGER=1 or cookie)
xdebug.mode=profile
xdebug.start_with_request=trigger
xdebug.output_dir=/tmp/xdebug

; MySQL slow query log (my.cnf)
; slow_query_log=1
; long_query_time=0.5
; log_queries_not_using_indexes=1

Common pitfalls

  • Profiling with Xdebug always on, distorting timings for everything.
  • Optimizing PHP loops when 90% of time is in SQL.
  • Testing with tiny local datasets that hide N+1 problems.

Key points

  • Profile before optimizing
  • Check query counts and slow logs
  • Use production-like data volumes

Further reading: Xdebug profiler

Practice questions

A page runs 400 queries. What's the likely cause and fix?

Answer

An N+1 pattern: a query per row inside a loop. Fetch related data in one query (JOIN or WHERE id IN (...)) and map it in PHP.

Why use trigger mode for the Xdebug profiler?

Answer

Profiling adds heavy overhead; trigger mode only profiles requests you explicitly mark, leaving others unaffected.

Open in the app to mark lessons complete, take notes and track your progress.