Web Performance Optimization

A practical guide to speeding up a WordPress site running the Jankx theme, based on real measurements taken on the Nobitour project. Every number in this document is a measured result, not an estimate.

Overview

Before optimizing, the important thing is knowing why a page is slow. Three groups of causes are most common:

TierSymptomHow to verify
PayloadFast TTFB but slow loadCompare size_download with and without --compressed
PHPTTFB accounts for nearly all total timeCompare time_starttransfer against time_total
NetworkSlow for users, fast on your machineMeasure from a different machine, not localhost

On localhost, bandwidth is effectively infinite, so the network tier is completely hidden. This is why many optimizations appear to do nothing when measured locally while making a large difference to real users.

Measured results

ItemBeforeAfterStatus
HTML transferred727,773 bytes257,490 bytesDONE 65% smaller
Median latency (warm, local)~1.44 s~1.25 sDONE
Content-Encoding: gzipabsentpresentDONE
Cache-Control (assets)absentimmutable 1 yearDONE
Cache-Control (HTML)absentno-storeDONE
Persistent object cacheabsentnot deployedTODO
Full-page cacheabsentnot deployedTODO
Disable WP_DEBUG in productiontruekept true (dev)NOT NEEDED
DISABLE_WP_CRONnot setnot setNOT NEEDED

The last two rows marked "not needed" are measured results, not assumptions. Both were enabled, re-measured, and reverted because neither helped. Details in Tier 2.

Measurement rules

  1. Measure before changing. Record a baseline you can reproduce.
  2. Re-measure the same way. Same run count, same warm conditions.
  3. Separate latency from payload. Shrinking payload does not reduce TTFB, and vice versa.
  4. Do not keep changes that do not help. A variable added for no gain is pure maintenance burden.
  5. Re-measure production-like. Numbers taken with Xdebug or WP_DEBUG on do not represent real users.
# Latency: run repeatedly, take the median, discard the first
php benchmarks/bench.php http --runs=7

# Compare TTFB against total time
curl -s -o NUL --compressed -w "ttfb=%{time_starttransfer}s total=%{time_total}s`n" http://nibitour.localhost/

# Compare compressed and uncompressed payload
curl -s -o NUL -w "identity: %{size_download} bytes`n" http://nibitour.localhost/
curl -s -o NUL --compressed -w "gzip    : %{size_download} bytes`n" http://nibitour.localhost/

Tier 1: Compression and cache headers

This is the cheapest change with the largest ratio. The homepage renders 727 KB of HTML and was sending it uncompressed. Enabling gzip alone cut the transferred data by 65%.

Enable gzip

nginx ships with gzip commented out. Uncomment it and add these settings to the http block:

sendfile        on;
tcp_nopush      on;

gzip              on;
gzip_vary         on;
gzip_proxied      any;
gzip_comp_level   6;
gzip_min_length   256;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/javascript
    application/x-javascript
    application/json
    application/xml
    application/rss+xml
    application/atom+xml
    image/svg+xml
    font/ttf
    font/otf
    application/vnd.ms-fontobject;
gzip_disable "msie6";

Cache headers for static assets

Build assets carry a hash in their filename and change on every deploy, so a hard cache is safe:

location ~* \.(?:css|js|mjs|woff2?|ttf|otf|eot|svg|png|jpe?g|gif|webp|avif|ico)$ {
    # Do NOT use `expires` here: it emits an additional Cache-Control
    # header that is weaker than the immutable one below.
    add_header Cache-Control "public, max-age=31536000, immutable" always;
    access_log off;
    try_files $uri =404;
}

Always use always in add_header. Without it nginx drops the header on responses such as 404 or 304, losing the cache header exactly when you need it.

Do not cache HTML

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass php_upstream;
    # A stale page is worse than a slow page.
    add_header Cache-Control "no-store, must-revalidate" always;
}

Brotli

Compresses 15-20% better than gzip. Official nginx has no Brotli; it requires the ngx_brotli module. Only do this after gzip is done and re-measured, because it adds another configuration step to an already fragile chain.

Tier 2: PHP runtime

Assumptions already ruled out

The three changes below are all plausible hypotheses. Each was enabled, measured, and found to make no difference, so all were reverted. They are recorded here so nobody measures them again.

HypothesisHow it was testedResult
Cron loopback slows every request Added DISABLE_WP_CRON, measured 6 runs No change (1.48-1.58 s)
WP_DEBUG causes overhead Set to false, measured CLI and HTTP No change (~1.4 s)
IMAP monitor runs per request Listed cron events, timed wp-cron.php directly Runs every 5 minutes, not on the request path

Explaining the curl_exec hotspot

The trace shows a single curl_exec call (~101 ms) with this call chain:

spawn_cron -> wp_remote_post -> WP_Http->request -> php::curl_exec

This is WP-Cron calling itself over HTTP loopback. But it only runs when an event is due. Listing the 16 scheduled events shows the heaviest job is the IMAP payment monitor on a 5-minute interval, and no event is overdue.

// List events and flag overdue ones
php your-script.php
// output: hook, next run time, interval, [OVERDUE] flag

Do not disable WP-Cron just because you see curl_exec in a profile. An intermittent loopback is not a per-request cost. Disabling it breaks payment monitoring without changing latency.

Actual time distribution

After enabling gzip, TTFB is 1.42 s out of 1.46 s total. Most of the remaining time is PHP, not data transfer. Hotspots by self time:

FunctionSelf timeNote
php::curl_exec101.4 msCron loopback, not per request
require_once::wp-settings.php68.6 msLoading plugins and themes
apply_filters45.6 msLong hook chain
Composer\Autoload\{closure\}41.9 msAutoloader filesystem lookups
_wp_array_get33.6 ms17,753 calls from WP_Theme_JSON->merge
WP_Theme_JSON::sanitize32.7 msRepeated theme JSON resolution
php::mysqli_query26.9 ms354 queries
php::file_exists + realpath36.8 msMostly from the autoloader

Self time by component:

ComponentSelf timeNote
wp-includes414.3 msWordPress core
themes/jankx293.5 msParent theme
plugins/polylang242.8 msTranslation plugin
Other136.8 msComposer, filesystem
themes/nibitour72.8 msChild theme

The two largest hotspots live in wp-includes and Polylang, not in Jankx code. That is why optimizing the object cache tier below has more impact than micro-optimizing inside the theme.

OPcache and JIT

On this environment OPcache is already enabled together with JIT in tracing mode, using an on-disk file cache:

opcache.enable              = 1
opcache.jit                 = tracing
opcache.file_cache          = C:/laragon/tmp/opcache
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 1

No change is needed locally. In production, set validate_timestamps=0 and deploy by restarting PHP, which removes the per-request file stat calls.

PHP files loaded at boot

Boot loads 1,396 files:

GroupFiles
wp-includes480
themes/nibitour401
themes/jankx368
plugins/polylang139

769 files across the two themes is a large number. Moving frontend-unused code behind on-demand autoloading would reduce it meaningfully. Re-measure over HTTP before concluding, since a CLI boot measurement does not reflect the production path.

Tier 3: Queries and object cache

The homepage runs 354 queries, many of them structurally duplicated:

QueryCountNote
SELECT * FROM wp_posts WHERE ID = ?46A warm post cache removes nearly all
SELECT option_name, option_value FROM wp_options52Identical, from get_option
SELECT FOUND_ROWS()17From pagination

A persistent object cache (Redis or Memcached) addresses both groups at once. This is the largest remaining PHP-level change.

Redis on this environment

Redis is already available at C:\laragon\bin\redis\redis-x64-5.0.14.1, but PHP has no matching extension:

# Check the extension
php -r "echo extension_loaded('redis') ? 'yes' : 'no';"
# -> no

# Current extension directory
php -i | Select-String "extension_dir"
# -> 41 dll files, no redis.dll

The redis extension must be enabled for PHP, then declared in wp-config.php:

define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);

This is an environment change and needs sign-off before proceeding. The lack of a persistent object cache is the root cause of both the 46 repeated post queries and the 52 repeated option queries.

Tier 4: Frontend

Once the server is compressing, what remains is browser-side:

TaskApproach
Render-blocking CSS/JSDefer non-critical scripts, use defer/async
Images without dimensionsAlways declare width/height to avoid layout shift
Render-blocking fontsfont-display: swap plus preload
Third-party scriptsDefer, or load after interaction

Tier 5: Full-page cache

This is the single biggest win for real users: HTML is pre-generated and PHP is not invoked at all on a cache hit.

The current environment runs nginx. Page cache and ESI are server-tier LiteSpeed features and will not work under nginx. Installing litespeed-cache under nginx does not give you full-page caching.

Two realistic options:

  1. Move to OpenLiteSpeed with litespeed-cache. Best option if the host supports it.
  2. Stay on nginx with a WordPress full-page cache plugin. Simpler when migration is impractical, but less effective because PHP still loads.

Once deployed, verify with the X-LiteSpeed-Cache or X-Cache header and re-measure:

curl -s -D - -o NUL http://nibitour.localhost/ | Select-String "X-LiteSpeed-Cache|X-Cache"

Pitfalls hit

All of the following actually occurred while applying these changes, and all are easy to repeat.

Reload succeeded but the config never applied

nginx -s reload signals the PID in logs/nginx.pid. If the master actually listening is a different process, the command reports success while the config is never loaded, and you debug the wrong thing.

# Which master is really listening?
Get-NetTCPConnection -LocalPort 80 -State Listen | ForEach-Object { $_.OwningProcess }

# Compare against the pid file
Get-Content C:\laragon\bin\nginx\nginx-1.28.2\logs\nginx.pid

Always verify headers after a reload. If the expected header does not appear, do not go deeper into the configuration.

Two conflicting Cache-Control headers

expires 1y; emits its own Cache-Control: max-age=31536000. Adding add_header Cache-Control "...immutable" beside it produces two headers with the same name, and which one wins is not predictable. Use add_header alone.

Duplicate PHP location

Adding a second location ~* \.php$ while an existing location ~ \.php$ remains makes the first block win and the new one silently ignored. nginx -t still reports success. Merge into one block.

Measuring on localhost and generalizing to the network

Loopback has no latency and effectively infinite bandwidth. A change that cuts payload 65% may show no local latency change while mattering a great deal to real users. Do not dismiss a payload optimization because local latency did not move.

Checklist

Recommended order, re-measuring after each step before moving on:

#StepStatus
1Record baseline: latency, TTFB, payload, query countDone
2Enable gzip and cache headers at the server tierDone
3Verify the headers actually appearDone
4Deploy persistent object cache (Redis)Needs approval
5Deploy full-page cacheNeeds approval
6Reduce render-blocking frontend scriptsNot started
7Reduce theme files loaded on the frontendNot started
8Re-measure everything and compare against baselinePending the above

Step 2 produced most of the improvement at close to zero cost and without touching theme code. Steps 4 and 5 require infrastructure changes and need a decision before proceeding.


Read next: Benchmark & Flame Graph →

← Back to Testing Guide