Astro Build Performance

Sixty-five seconds just to build out the first pages of the #tech pages. Why? Because they are reliant on a complex function that gets a tag map. So let’s understand how pages are built for a route, from what I gather.

function doComplexThing() {
	const things = [];
	// do the thing

	// return the data
	return data;
}

The getStaticPaths method returns an array of pages and their data. This is called once. So that complex function? Not really a problem here. Then Astro renders each page that getStaticPaths returns. The problem is that I need that complex function’s data here too. Without calling it here, we build these pages in 10 seconds. With it, 65.

export async function getStaticPaths() {
	const things = doComplexThing();
	return things.map(thing => ({
		params: {
			tag: thing
		}
	}));
}

Okay, now we have options. We could just put that data in the paths’ props. But it is used by a component in the page that is rendered. We could pass that data as a prop to that component. But it would be easier to call it inside the component. 65 seconds. And that’s just a fraction of the pages that need to build.

And that leads to an old trick from my PHP days. Caching the data of a function and returning it the next time we try to access it.

export let cachedThings: any[] | undefined = undefined;
export function doComplexThing() {
	if (cachedThings) return cachedThings;
	
	const things = [];
	// do the thing
	
	// cache it
	cachedThings = things;

	// return the data
	return data;
}

Now when we call doComplexThing() the first time, it runs the complex code. But then we hit it hundreds of more times and returns the cache.

Hey! Did you enjoy what you just read? Like buttons and shares may stoke the ego, but coffee fuels the body. No subscription, just $3.

Buy Me a Coffee!

Other posts you may enjoy!