Do Not Use Readable Store in Svelte

Published: June 6, 2024

Do Not Use Readable Store in Svelte

Background

If you are using Svelte, you might know that there are several types of stores for state management, with two being readable and writable stores.

As name suggests, a writable store is an mutable store which lets you change its state while a readable store is only good for reading.

Then the question is, if readable store is static, why do we need it in the first place? Can't we just store that information in an object in some js file and get the data from there?

Would it make a difference?

Context

I used to keep most the static information about my app (E.g. color scheme, screen breakpoints) in readable stores.

As I'm trying to reduce build size of my site and increase its speed, Im investigating potential areas for improvement. So I decided to check what difference it'd make to move those variables out from readable store to plain vanilla js objects.

So I decided to do a small experiment to see the effect of readable store on the build size and speed of my website.

Method

We create a small static app that shows numbers from 0-99, and we'll be keeping these numbers in 2 difference formats.

1. Plain Vanilla JS Object

Below is the page we'll be serving. It's just listing of all numbers from 0-99.

// src/routes/+page.svelte
<script>
	import { numbers } from "/src/data/numbers";
</script>

<div style="display:flex; flex-flow:wrap; margin:24px">
	{#each numbers as number}
		<span style="margin: 4px;">{number}</span>
	{/each}
</div>

Where the data is obtained from a JS object. Below code generates an array of numbers ranging between 0-99 and exports that array.

// src/data/numbers.js

let limit = 100;
export const numbers = Array.from({ length: limit }).map((_, index) => index);

2. Svelte Readable Store

Below is the page we'll be serving in the readable version, with only difference of adding $ (dollar) sign in front of the numbers variable as this variable is now a stored variable.

// src/routes/+page.svelte 

<script>
	import { numbers } from "/src/data/numbers";
</script>

<div style="display:flex; flex-flow:wrap; margin:24px">
	{#each $numbers as number}
		<span style="margin: 4px;">{number}</span>
	{/each}
</div>

Where the data is obtained from a JS object. This is same as previous array, with only difference of enclosing it in a readable function.

// src/data/numbers.js

import { readable } from "svelte/store";
let limit = 100;
export const numbers = readable(
 Array.from({ length: limit }).map((_, index) => index)
);

Below shows the simple page that is created as a result:

App view of numbers

Pretty simple stuff right? Now let's see the performance difference among these 2 versions of an app, that produces identical results to the users.

Results

1. Build Size

We go ahead and build these 2 files and see the size of the build folder. this should give us an idea about whether readable store is causing any overhead.

Build size

You can see above that the build folder where we used readable store turns out to be 205kb while JS version ends up as 193kb. The difference between these files is negligible I'd say.

When I increase the numbers from 99 to 99999, the build size difference was a mere 700KB, so even when you handle large objects, it seems like readable does not cause a large overhead when it comes to build size.

But, since these 2 constructs yield the exact same result, there is no point in choosing readable over plain-vanilla JS because JS has simpler syntax as well as smaller build size.

2. Page load speed

Now let's assume we have another page in our website, which is an About page. This page does not use this numbers object at all, so let's see how these 2 constructs influence the loading speed for an unrelated page in our website.

Below is how the setup looks like.

About

Note that, the numbers are not used whatsoever in the About page. We now see how it will impact the performance of this page.

This time we increase the numbers to 99,999 to see the performance difference clearly.

Speed of plain about page

Above picture shows the speed of loading the About page using plain JS. The loading is finished in 62 ms.

Speed of readable about page

Above picture shows the speed of loading the About page using readable store. The loading is finished in 77 ms.

Again, we see that plain JS has outperformed readable store.

Conclusion

Since we only have a sample size of one, and that the difference between these 2 options is not huge, some of you may think that there is still not strong evidence that supports plain JS against readable store.

But, why use a more complex readable store syntax that may increase your build size and reduce your page speed. It doesn't make sense to me.

Do you know any benefits to using readable over plain JS? Let me know in the comments below.

Until then, happy hacking!

Programmer

Leave comment

Comments

Check out other blog posts

Create A Simple and Dynamic Tooltip With Svelte and JavaScript

2024/06/19

Create A Simple and Dynamic Tooltip With Svelte and JavaScript

JavaScriptSvelteSimpleDynamicTooltipFront-end
Create an Interactive Map of Tokyo with JavaScript

2024/06/17

Create an Interactive Map of Tokyo with JavaScript

SvelteSVGJavaScriptTailwindInteractive MapTokyoJapanTokyo Metropolitan Area23 Wards
How to Easily Fix Japanese Character Issue in Matplotlib

2024/06/14

How to Easily Fix Japanese Character Issue in Matplotlib

MatplotlibGraphChartPythonJapanese charactersIssueBug
Book Review | Talking to Strangers: What We Should Know about the People We Don't Know by Malcolm Gladwell

2024/06/13

Book Review | Talking to Strangers: What We Should Know about the People We Don't Know by Malcolm Gladwell

Book ReviewTalking to StrangersWhat We Should Know about the People We Don't KnowMalcolm Gladwell
Most Commonly Used 3,000 Kanjis in Japanese

2024/06/07

Most Commonly Used 3,000 Kanjis in Japanese

Most CommonKanji3000ListUsage FrequencyJapaneseJLPTLanguageStudyingWordsKanji ImportanceWord Prevalence
Replace With Regex Using VSCode

2024/06/07

Replace With Regex Using VSCode

VSCodeRegexFindReplaceConditional Replace
Increase Website Load Speed by Compressing Data with Gzip and Pako

2024/06/05

Increase Website Load Speed by Compressing Data with Gzip and Pako

GzipCompressionPakoWebsite Load SpeedSvelteKit
Find the Word the Mouse is Pointing to on a Webpage with JavaScript

2024/05/31

Find the Word the Mouse is Pointing to on a Webpage with JavaScript

JavascriptMousePointerHoverWeb Development
Create an Interactive Map with Svelte using SVG

2024/05/29

Create an Interactive Map with Svelte using SVG

SvelteSVGInteractive MapFront-end
Book Review | Originals: How Non-Conformists Move the World by Adam Grant & Sheryl Sandberg

2024/05/28

Book Review | Originals: How Non-Conformists Move the World by Adam Grant & Sheryl Sandberg

Book ReviewOriginalsAdam Grant & Sheryl SandbergHow Non-Conformists Move the World
How to Algorithmically Solve Sudoku Using Javascript

2024/05/27

How to Algorithmically Solve Sudoku Using Javascript

Solve SudokuAlgorithmJavaScriptProgramming
How I Increased Traffic to my Website by 10x in a Month

2024/05/26

How I Increased Traffic to my Website by 10x in a Month

Increase Website TrafficClicksImpressionsGoogle Search Console
Life is Like Cycling

2024/05/24

Life is Like Cycling

CyclingLifePhilosophySuccess
Generate a Complete Sudoku Grid with Backtracking Algorithm in JavaScript

2024/05/19

Generate a Complete Sudoku Grid with Backtracking Algorithm in JavaScript

SudokuComplete GridBacktracking AlgorithmJavaScript
Why Tailwind is Amazing and How It Makes Web Dev a Breeze

2024/05/16

Why Tailwind is Amazing and How It Makes Web Dev a Breeze

TailwindAmazingFront-endWeb Development
Generate Sitemap Automatically with Git Hooks Using Python

2024/05/15

Generate Sitemap Automatically with Git Hooks Using Python

Git HooksPythonSitemapSvelteKit
Book Review | Range: Why Generalists Triumph in a Specialized World by David Epstein

2024/05/14

Book Review | Range: Why Generalists Triumph in a Specialized World by David Epstein

Book ReviewRangeDavid EpsteinWhy Generalists Triumph in a Specialized World
What is Svelte and SvelteKit?

2024/05/13

What is Svelte and SvelteKit?

SvelteSvelteKitFront-endVite
Internationalization with SvelteKit (Multiple Language Support)

2024/05/12

Internationalization with SvelteKit (Multiple Language Support)

InternationalizationI18NSvelteKitLanguage Support
Reduce Svelte Deploy Time With Caching

2024/05/11

Reduce Svelte Deploy Time With Caching

SvelteEnhanced ImageCachingDeploy Time
Lazy Load Content With Svelte and Intersection Oberver

2024/05/10

Lazy Load Content With Svelte and Intersection Oberver

Lazy LoadingWebsite Speed OptimizationSvelteIntersection Observer
Find the Optimal Stock Portfolio with a Genetic Algorithm

2024/05/10

Find the Optimal Stock Portfolio with a Genetic Algorithm

Stock marketPortfolio OptimizationGenetic AlgorithmPython
Convert ShapeFile To SVG With Python

2024/05/09

Convert ShapeFile To SVG With Python

ShapeFileSVGPythonGeoJSON
Reactivity In Svelte: Variables, Binding, and Key Function

2024/05/08

Reactivity In Svelte: Variables, Binding, and Key Function

SvelteReactivityBindingKey Function
Book Review | The Art Of War by Sun Tzu

2024/05/07

Book Review | The Art Of War by Sun Tzu

Book ReviewThe Art Of WarSun TzuThomas Cleary
Specialists Are Dead. Long Live Generalists!

2024/05/06

Specialists Are Dead. Long Live Generalists!

SpecialistGeneralistParadigm ShiftSoftware Engineering
Analyze Voter Behavior in Turkish Elections with Python

2024/05/03

Analyze Voter Behavior in Turkish Elections with Python

TurkeyAge Analysis2018 ElectionsVoter Behavior
Create Turkish Voter Profile Database With Web Scraping

2024/05/01

Create Turkish Voter Profile Database With Web Scraping

PythonSeleniumWeb ScrapingTurkish Elections
Make Infinite Scroll With Svelte and Tailwind

2024/04/30

Make Infinite Scroll With Svelte and Tailwind

SvelteTailwindInfinite ScrollFront-end
How I Reached Japanese Proficiency In Under A Year

2024/04/29

How I Reached Japanese Proficiency In Under A Year

JapaneseProficiencyJLPTBusiness
Use-ready Website Template With Svelte and Tailwind

2024/04/25

Use-ready Website Template With Svelte and Tailwind

Website TemplateFront-endSvelteTailwind
Lazy Engineers Make Lousy Products

2024/01/29

Lazy Engineers Make Lousy Products

Lazy engineerLousy productStarbucksSBI
On Greatness

2024/01/28

On Greatness

GreatnessMeaning of lifeSatisfactory lifePurpose
Converting PDF to PNG on a MacBook

2024/01/28

Converting PDF to PNG on a MacBook

PDFPNGMacBookAutomator
Recapping 2023: Compilation of 24 books read

2023/12/31

Recapping 2023: Compilation of 24 books read

BooksReading2023Reflections
Create a Photo Collage with Python PIL

2023/12/30

Create a Photo Collage with Python PIL

PythonPILImage ProcessingCollage
Detect Device & Browser of Visitors to Your Website

2024/01/09

Detect Device & Browser of Visitors to Your Website

JavascriptDevice DetectionBrowser DetectionWebsite Analytics
Anatomy of a ChatGPT Response

2024/01/19

Anatomy of a ChatGPT Response

ChatGPTLarge Language ModelMachine LearningGenerative AI