How Faster Is A Static-Generated Webpage?

One of the main reasons to prefer pre-rendered websites, also known as static-generated websites, over traditional ones is the loading speed. 

A faster website provides a better user experience: according to Neil Patel, you lose 40% of your visitors if it takes more than 3 seconds to load the webpage. It’s also an important factor to take into account in your SEO strategy, as confirmed by Google.

But how faster is a static-generated webpage, really? That’s what I decided to find out today.

I opened my Cowriters Symfony application, added a test endpoint, and wrote down a few instructions to perform.

I’m not going to compare a static generator like Gatsby or Hugo with a traditional web framework like Symfony, since the two have an entirely different architecture. Instead, I’m going to stick to Symfony throughout the whole experiment. 

I first picked a random text in the database and set the number of trials to 10000. Of course, every trial is performed using the same machine.

$slug = 'how-i-got-into-software-development-9775ec3ea0ab0020';
$text = $repository->findOneBySlug($slug);
$trials = 10000;

I then requested the same webpage 10,000 times using a dynamic approach. The web server parses a Twig template, fill in the placeholders with the relevant data, and returns a Response object ready to send back to the web client over HTTP.

$beg_time = microtime(true);
for($i = 0 ; $i < $trials ; $i++){
    $args = array('text' => $text);
    $this->render("pages/article/article.html.twig", $args);
}
$end_time = microtime(true);
$result1 = ($end_time - $beg_time) * 1000 / $trials;

I do the same thing with the static approach after the build phase. The build phase consists of pre-rendering the relevant HTML file from the Twig template and storing it in the web server. Rendering the resulting file consists in reading the pre-rendered file and sends the data over HTTP as an HTML response.

//Build phase
$build_time = $generator->build([
    [
        'template' => 'pages/article/article.html.twig',
        'dest' => "/words/{$slug}",
        'args' => ['text' => $text]
    ]
]);
$build_time *= 1000;

//Rendering phase
$beg_time = microtime(true);
for($i = 0 ; $i < $trials ; $i++){
    $this->renderStatic("/words/{$slug}");
}
$end_time = microtime(true);
$result2 = ($end_time - $beg_time) * 1000 / $trials;

The result is undeniable: over 10k occurrences, static rendering is 6 times faster on average than dynamic rendering (0.27ms vs 0.05ms, with a build time of 0.37ms).

This is a huge improvement over traditional web development. The website scales better, and the individual user experience is more satisfying. And the more data there is to proceed, the faster static rendering becomes compared to dynamically rendering the page each time a visitor shows up.