I did it. I finally managed to optimise loading time of the site to just 0.5 seconds (proof below) in mobile and desktop. 

Uptrends score

Here is speed check at Gtmetrix.com

gtmetrix speed

You may have a very beautiful wp site but you compromise for speed. What is the use if it doesn’t reach anybody. Website speed has a huge impact on best user experience, SEO, and conversion rates. This is 2022 people, not like 2000’s where you launch html pages.

People just don’t have the patience to wait for loading.

Speed is the key to Google organic rankings, slow sites aren’t going anywhere and won’t have any competitive edge. Remember the bounce rate increases by 30% for every 1s.  

The work took me years of planning, thinking and working. Got to proudly say, I have the fastest WordPress site in the world (I am also speed addict).  At the end of the day, Speed is a Game changer!

The secret to speed is keep it plain and simple. Small the page size equals fast loading (Aim for below 200kb for best speeds). 

The most likely culprits are images, css and js files. Think about the math first. If you cut down 50Kb of WordPress code, assuming your site has 1000 visitors, you would help save 50mb of cellular data and bandwidth to your users. (Don’t forget your users are paying for mobile data) This is huge for even a small website.

Recommended Speed Metrics

Keep an eye on these importance performance metrics for mobile speed.

  • Largest Contentful Paint (LCP):  within 2.5 seconds
  • First Input Delay (FID) – less than 100 milliseconds.
  • Cumulative Layout Shift (CLS): less than 0.1.
  • Time to first byte (TTFB): 200ms (as per Google)
  • Total Http requests – under 10
  • Fully loaded time – less than 2s 
  • Page size – Less than 200kb

WP Speed Tips

I would suggest the following 80 optimizations and improvements.

  1. Get rid of frontend bloats (sliders, background videos, music)
  2. Get rid of heavy images, compress them for speed. This is the 90% cause for slow pages. (use smush, imagify for bulk processing to compress jpg/png)
  3. Install & run lightweight WordPress theme (eg. Neve, Astra, Generatepress)
  4. Cut down google fonts usage (more the fonts increase loading times, try to use one or two max). 
  5. Reduce CSS file size and remove Unused css for optimal content delivery (minify css). Reduce unused rules from stylesheets and defer CSS not used for above-the-fold content to decrease bytes consumed by network 
  6. Use lazy load to defer image load after user interaction makes a huge diff 
  7. Reduct Jquery load and remove defer loading for better paint. (Minify js)
  8. Reduce the resource usage of WordPress plugins. Deactivate orRemove unwanted plugins.
  9. Remove unused old wordpress themes.
  10. Update to latest WordPress versions, themes and plugins.
  11. Optimize wordpress database (every month tables)
  12. Lockdown wp-login page from brute force attacks from bots (consumes resource)
  13. Enable Brotli compression in Cloudfloare 
  14. Enable Gzip for speed – mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80% Compression reduces response times by reducing the size of the HTTP response. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today’s Internet traffic travels through browsers that claim to support gzip. Go to Cpanel > Optimise website > Enable compress all content
  15. Use robots.txt for Google crawler to block indexing spam pages  (if you are under spam attack, this reduces server usages). For example..
    • User-agent: *
    • Disallow: /wp-admin/
    • Allow: /wp-admin/admin-ajax.php
    • Disallow: /?s=
    • Disallow: /search/
    • Sitemap: https://best-citizenships.com/sitemap.xml
  16. Check for hacks and malicious content (base64) which can lead to painfully slow content loading. Manually inspect code
  17. Use a security plugin preventing hack attacks (cuts server resource use). I used optimised wordfence plugin and I found that site performance increased. (Tip: disable live traffic for speed)
  18. Use CDN for speed for example, (cut down latency)
  19. Update to latest php version 8 or more (for speed)
  20. Slow servers have poor TTFB (time to first byte) very high can cause website slow down dramatically. It cannot be overlooked. It depends on Geolocation. Use server cache and CDN geo caching.
  21. Use WP caching plugin (increases speed and reduces load)
  22. Page builders consume memory, try to avoid them.
  23. Enable a Gzip compression in Cpanel settings server
  24. Serve images in next-gen formats – Image formats like WebP and AVIF often provide better compression than PNG or JPEG, which means faster downloads and less data consumption.
  25. Avoid layout shifts (content elements jumping before load). This increases CLS used for google ranking.
  26. Avoid multiple redirects (slow down page speed times)
  27. Keep the DOM size low. A large DOM will increase memory usage, cause longer style calculations, and produce costly layout reflows. 
  28. Optimize apache/nginx server settings for speed.
  29. CSS gradients in code spend a lot of time painting painfully slow rendering. Replace the gradient code with png backgrounds.
  30. Consider VPS or dedicated or cloud server from reputable hosting providers for speed.
  31. Social media icons that pull likes or shares can bog down your site during peak times. 
  32. Deliver critical JS/CSS inline and deferring all non-critical JS/styles.
  33. Increase browser caching time .
  34. Reduce HTTP requests (trim it to 10)
  35. Use load balancing for high traffic servers for speed. (eg. www1, www2)
  36. Cloudflare Speed Optimisation – Enable http/2, APO (paid $5), Argo (paid), Railgun, Enable HTML cache, Brotli, Autominify (CSS, JS, HTML), Enable Rocket Loader (may defer js paint times). Create a page rule for cache with htttps://example.com/*
  37. Defer YouTube embedded videos (disable auto play videos) to speed up slow loading . (Use loading=“lazy” in the iframe code.)
  38. Ads can also slow page loading during high traffic (network latency)
  39. Get rid of base64 image code loading raw (this increases page size)
  40. Form plugins must load only where form pages are loaded. (Do not load it everywhere)
  41. Remove any or all junk data (meta, smileys, emoticons etc)
  42. Compress pdf (brochures, reports etc) before upload. You can use ilovepdf.com
  43. Use menu cache if your plugin supports
  44. Increase the memory of PHP in php.ini to atleast 256M
  45. Reduce WordPress resources – Disable pings, comments and set blog type to summary, set login attempts to 3
  46. Keep an eye on Apache or server errors – Any errors or warnings can slowdown your website.
  47. Guard against DOS attacks (force captcha) to flush out bots.
  48. Cookie free domains – cookies are unnecessary network traffic. 
  49. Avoid empty src or href
  50. Put JavaScript at bottom
  51. Try to use CSS Sprites and image maps (instead of downloading too many requests for small images eg. flags)
  52. Google analytics code can be remove if unused (can cause milliseconds of degrade). Remove the plugin.
  53. Using Fontello and Fontawesome icons can be slow. Use @font-face, cut the font size (include only the font icons in font file)

    @font-face {
        font-family: ‘Awesome Font’;   font-style: normal;   font-weight: 400;   font-display: swap; /* or block, swap, fallback, optional */   src: local(‘Awesome Font’),        url(‘/fonts/awesome-l.woff2’) format(‘woff2’), /* will be preloaded */        url(‘/fonts/awesome-l.woff’) format(‘woff’),        url(‘/fonts/awesome-l.ttf’) format(‘truetype’),        url(‘/fonts/awesome-l.eot’) format(’embedded-opentype’);   unicode-range: U+000-5FF; /* Latin glyphs */ }
  54. Social media shares and feeds can and do impact speed and performance 
  55. Disable user registrations  (increase the database and thus slow queries)
  56. WPbakery or elementor page builders can be optimised to serve fast loading content.
  57. Shortcodes are slower than Html but too many shortcakes can be a degrade.
  58. Google map plugin can have overheads can be painfully laggy on slower connections.,
  59. Delete drafts, revisions and empty trash posts to free up database.
  60. Paginate posts, pages and comments.
  61. Shut down unused TCP/UDP ports in your server. (Prevent port scanning)
  62. Limit posts on blog feed RSS/XML
  63. InnoDB performs slightly better than MyISAM storage.
  64. Troubleshoot slow database queries using Query monitor plugin.
  65. Enable Hotline protection to prevent draining resources from server.
  66. Enable WP_DEBUG logging to troubleshoot WordPress errors.
  67. Disable too many Cron jobs running on the server.
  68. Clear JS from the Critical Rendering PathClear JS from the Critical Rendering Path (use async or defer)
  69. Comment can bring in lot of performance issues (especially lot of spam comments). Disable or lazy load optimise or just use third party plugin to handle.
  70. DNS prefetch and pre-connect is a great way to speed from background.
    <link rel="dns-prefetch" href=“//example.com"> 
    
    <link rel="dns-prefetch" href="//fonts.googleapis.com/">
  71. AMP might just work if you are only focused on mobile speed. Use AMP for WordPress plugin.
  72. Install memcache and redis frameworks
  73. Disable in Cpanel to conserve memory – Webstats, Mailman, SpamAssasin
  74. Use WP CLI to optimise images on command line.
  75. Use JSON instead of XML – Speaking of which, native PHP functions such as json_encode() and json_decode() are incredibly fast, which is why using JSON is preferable to using XML
  76. Disable counters or traffic statistics with real time updates (this increases load) in php code
  77. As a coder, use php native functions for speed along with isset(), single quotes (faster than double), triple equal === faster than double ==
  78. Running out of disk space can cause server to crash or stall or memory hog or performance issues. Double check
  79. Fine tune php.ini for performance.
  80. Calls to file system functions (search, count etc) can pull the server down
  81. Use fast fileserver for serving static content (eg. static.example.com)
  82. Incorrect directives placed at .htaccess can cause site to run slow or (frequent Internal server errors) 
  83. Turn off testing mode or debug mode in page builders
  84. Use the best performance server software – LiteSpeed can handle high CPU plugins more than Nginx/Apache
  85. Inspect source code. Get rid of unnecessory junk code inserted. Use chrome dev tools to inspect. You can use page loading time pressing

Slow plugins List

These plugins can have big impact on shared hosting plans

  • Contact Form 7
  • All in one SEO
  • Disqus Comment System
  • Jetpack
  • Backups
  • Translations
  • WPML
  • WP Mobile menu
  • WP Bakery, Beaver Builder, Elementor
  • WP Google maps 
  • Broken Link Checker
  • NextGen Gallery
  • Revolution Slider
  • Social plugins (addthis, share, buttons)
  • YARP
  • WordFence (can be fast if tuned properly), Sucuri
  • EWWW Image Optimizer
  • Similar Posts / Related posts
  • WordPress Multilingual (WPML)
  • WP Super Cache (and most other caching plugins)

Coding Tips for Speed

Webber’s points: (source GitHub)

  • If a method can be static, declare it static. Speed improvement is by a factor of 4.
  • echo is faster than print.(* compare with list from phplens by John Lim)
  • Use echo’s multiple parameters instead of string concatenation.
  • Set the maxvalue for your for-loops before and not in the loop.
  • Unset your variables to free memory, especially large arrays.
  • Avoid magic like __get, __set, __autoload
  • require_once() is expensive
  • Use full paths in includes and requires, less time spent on resolving the OS paths.
  • If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
  • See if you can use strncasecmp, strpbrk and stripos instead of regex
  • str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  • If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  • It’s better to use select statements than multi if, else if, statements.
  • Error suppression with @ is very slow.
  • Turn on apache’s mod_deflate
  • Close your database connections when you’re done with them
  • $row[’id’] is 7 times faster than $row[id]
  • Error messages are expensive
  • Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
  • Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  • Incrementing a global variable is 2 times slow than a local var.
  • Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
  • Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  • Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  • Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
  • Methods in derived classes run faster than ones defined in the base class.
  • A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
  • Surrounding your string by ‘ instead of ” will make things interpret a little faster since php looks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.
  • When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
  • A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
  • Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
  • Cache as much as possible. Use memcached – memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
  • When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
    Ex.
    1.if (strlen($foo) < 5) { echo “Foo is too short”; }vs.1.if (!isset($foo{5})) { echo “Foo is too short”; }Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.
  • When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
  • Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  • Do not implement every data structure as a class, arrays are useful, too
  • Don’t split methods too much, think, which code you will really re-use
  • You can always split the code of a method later, when needed
  • Make use of the countless predefined functions
  • If you have very time consuming functions in your code, consider writing them as C extensions
  • Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
  • Excellent Article about optimizing php by John Lim

As Reihold Webber pointed to a post from John Lim (found this article copied without state the source here), then i investigate further and truly that is an excellent best practice tutorial for optimizing the php code performance, covered almost all aspects from low level webserver configuration, PHP configuration, coding styling, and performace comparisson as well.

Another good practice for better php performance as written in cluesheet.com are:

  • Do use single quotes over double quotes.
  • Do use switch over lots of if statements
  • Do avoid testing loop conditionals with function tests every iteration eg. for($i=0;i<=count($x);$i++){…
  • Do use foreach for looping collections/arrays. PHP4 items are byval, greater than PHP5 items are byref
  • Do consider using the Singleton Method when creating complex PHP classes.
  • Do use POST over GET for all values that will wind up in the database for TCP/IP packet performance reasons.
  • Do use ctype_alnum,ctype_alpha and ctype_digit over regular expression to test form value types for performance reasons.
  • Do use full file paths in production environment over basename/fileexists/open_basedir to avoid performance hits for the filesystem having to hunt through the file path. Once determined, serialize and/or cache path values in a $_SETTINGS array. $_SETTINGS[“cwd”]=cwd(./);
  • Do use require/include over require_once/include_once to ensure proper opcode caching.
  • Do use tmpfile or tempnam for creating temp files/filenames
  • Do use a proxy to access web services (XML or JSOM) on foreign domains using XMLHTTP to avoid cross-domain errors. eg. foo.com<–>XMLHTTP<–>bar.com
  • Do use error_reporting (E_ALL); during debug.
  • Do set Apache allowoverride to “none” to improve Apache performance in accessing files/directories.
  • Do use a fast fileserver for serving static content (thttpd). static.mydomain.com, dynamic.mydomain.com
  • Do serialize application settings like paths into an associative array and cache or serialize that array after first execution.
  • Do use PHP output control buffering for page caching of heavilty accessed pages
  • Do use PDO prepare over native db prepare for statements. mysql_attr_direct_query=>1
  • Do NOT use SQL wildcard select. eg. SELECT *
  • Do use database logic (queries, joins, views, procedures) over loopy PHP.
  • Do use shortcut syntax for SQL insers if not using PDO parameters parameters. eg. INSERT INTO MYTABLE (FIELD1,FIELD2) VALUES ((“x”,”y”),(“p”,”q”));

Useful Code

Disable JS composer frontend loading

// Remove WPB CSS & JS on frontend

/*

function remove_wpb_js_css() {

    if (!is_admin()) {

        wp_dequeue_style('js_composer_front');

        wp_deregister_style('js_composer_front');

        wp_dequeue_script('wpb_composer_front_js');

        wp_deregister_script('wpb_composer_front_js');

    }

}

add_action( 'wp_enqueue_scripts', 'remove_wpb_js_css', 99 );

//disable schema aiseo

Disable Schema AISEO 

add_filter( 'aioseo_schema_disable', 'aioseo_disable_schema' );

function aioseo_disable_schema( $disabled ) {

   return true;

}

Preload featured image

/* Preload featured image */

add_action( 'wp_head', function(){

$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full'); 

echo '<link rel="preload" as="image" href="'.$featured_img_url.'"/>';

});

Noindex search pages

/* No index search results */
add_action( 'wp_head', function(){

if ( is_search() ) { 

    echo '<meta name="robots" content="noindex, nofollow" />';

}
});

Remove dash icons

// Remove dashicons in frontend for unauthenticated users

add_action( 'wp_enqueue_scripts', 'bs_dequeue_dashicons' );

function bs_dequeue_dashicons() {

    if ( ! is_user_logged_in() ) {

        wp_deregister_style( 'dashicons' );

    }

}