This benchmark compares performance of JSON serialization and HTML template rendering. In a server returning HTML or JSON the main difference is with the serialization. So I wanted to know how much difference it makes to return a JSON response vs HTML response. So I just tested json serialization vs html template rendering in Go.

Benchmarking Setup

The setup is simple, with go test, main_test.go

package main

import (
	"bytes"
	"encoding/json"
	"testing"
	"text/template"

	"github.com/flosch/pongo2/v6"
)

// Example struct to marshal
type SimpleStruct struct {
	Field1 string `json:"field1"`
	Field2 int    `json:"field2"`
}

// BenchmarkJsonMarshalling tests the performance of JSON marshaling.
func BenchmarkJsonMarshalling(b *testing.B) {
	// setup any necessary data for the benchmark
	data := SimpleStruct{
		Field1: "example",
		Field2: 123,
	}

	// Run the benchmark
	for i := 0; i < b.N; i++ {
		_, err := json.Marshal(data)
		if err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkHTMLRenderingWithPongo(b *testing.B) {
	tpl, err := pongo2.FromString("Hello {{ name }}!")
	if err != nil {
		panic(err)
	}

	// Run the benchmark
	for i := 0; i < b.N; i++ {
		_, err := tpl.Execute(pongo2.Context{"name": "florian"})
		if err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkHTMLRenderingWithTemplate(b *testing.B) {
	data := map[string]string{
		"Field1": "example",
	}

	tmpl := template.Must(template.New("test").Parse("Hello {{ .Field1 }}!"))
	// Run the benchmark
	for i := 0; i < b.N; i++ {
		memory := new(bytes.Buffer)
		err := tmpl.Execute(memory, data)
		if err != nil {
			b.Fatal(err)
		}
	}
}

Benchmarking Results

BenchmarkJsonMarshalling-14                      9746420               103.6 ns/op
BenchmarkHTMLRenderingWithPongo-14               2557006               467.0 ns/op
BenchmarkHTMLRenderingWithTemplate-14            7220666               168.7 ns/op

My Thoughts

JSON serialization is bit faster than HTML template rendering.

But,

  • Server Side rendered app is more consistent in terms of state management.
  • SSR removes the complexity of syncing the state between client and server.
  • There security advantages of server side rendering.
  • In large projects where we keep interfacing the client and server with JSON, and we endup having many specific endpoints or a complex graphQL server with lots of security checks for fields that’s not safe to expose.
  • If we keep endpoints RESTful, we endup having more endpoints and more http requests which results in more latency.
  • Considering advantages of server side rendering, the cost isn’t that much, in my opinion It’s so much better.