DEV Community

Cover image for The Beginner's Guide to Caching: How to Improve Code Performance
Rishabh Pawar
Rishabh Pawar

Posted on • Updated on

The Beginner's Guide to Caching: How to Improve Code Performance

Introduction

Caching is a powerful technique for improving code performance.In this beginner's guide to caching, we'll explore what caching is, how it works, and how you can use it to optimize your code and deliver faster.

What is caching ?

Caching is a technique of storing frequently accessed data in a fast-access memory, such as RAM or a local hard drive, so that it can be quickly retrieved when needed. This helps to improve the speed and efficiency of computer programs, since accessing data from memory is much faster than accessing it from a slower storage device like a disk.

Why do we need caching ?

We need caching because it can greatly improve the performance of applications and systems that rely on frequently accessed data. Caching works by storing frequently accessed data in a location that is easily and quickly accessible, such as in RAM or on a local disk. When the application needs to access this data again, it can retrieve it from the cache rather than having to re-fetch it from a slower storage medium like a disk or a remote server. This results in faster data access times and can greatly improve the overall performance and responsiveness of an application.

Additionally, caching can also help to reduce the workload on servers and databases. By caching frequently accessed data, fewer requests need to be made to the server or database, which can help to reduce server load and improve the scalability of the system.

Overall, caching is an essential tool for optimizing the performance of applications and systems that rely on frequently accessed data. It can greatly improve the speed and efficiency of data access, reduce server load, and ultimately provide a better user experience.

How I Explored Caching Without Even Knowing It?

Image description

When I was working on my project, skribbl.io, I implemented a custom music player that allowed users to request songs by typing ".play xyz" (where "xyz" is the name of the song). To retrieve the song details, I used Socket.IO to send the song title to the backend, which then made a request to the YouTube Data API. However, this was a very heavy task that caused my application to exceed the API limit quickly, especially if users requested the same song multiple times.

To optimize my application and prevent it from exceeding the API limit, I implemented a caching mechanism. I created an object called "songs" that stored the song title and URL. Before making a request to the YouTube Data API, I checked if the user input already existed in the "songs" object. If it did, I simply extracted the song data from the object instead of making a new API call. This greatly reduced the number of API calls my application needed to make, improving overall performance.

By implementing caching, I was able to optimize my application and reduce the workload on my server. This is a great example of how caching can be used to improve code performance and prevent unnecessary API calls.

const songs = {};
const songNameArray = [];
const YOUTUBE_SONGS_ITEMS_API = "https://www.googleapis.com/youtube/v3/search";
const YOUTUBE_API_KEY = process.env.API_KEY;

// trimming and lower casing the search input value.
    const trimmedSearchInput = searchInput.trim().toLowerCase();

 const foundSong = songNameArray.find((songName) =>
      songName.includes(trimmedSearchInput)
    );
 if (foundSong) {
      // const songName = songNameArray[index];
      const songObject = songs[foundSong];
      console.log("Song found no need to make request!");
    } else {
      makeRequest(trimmedSearchInput);
    }

//Make request function...

const makeRequest = async (trimmedSearchInput) => {
      console.log("Song did not found,request made!");
      try {
        const res = await fetch(
          `${YOUTUBE_SONGS_ITEMS_API}?part=snippet&maxResults=1&q=${trimmedSearchInput}&type=video&videoCategoryId=10&key=${YOUTUBE_API_KEY}`
        );
        const data = await res.json();
        const videoId = data.items[0].id.videoId;
        youtubedl(`https://www.youtube.com/watch?v=${videoId}`, {
          dumpSingleJson: true,
          noCheckCertificates: true,
          noWarnings: true,
          preferFreeFormats: true,
          addHeader: ["referer:youtube.com", "user-agent:googlebot"],
        }).then((output) => {
          const audioFormats = output.formats.filter(
            (f) => f.acodec !== "none"
          );
          const bestAudio = audioFormats.reduce((prev, curr) =>
            prev.abr > curr.abr ? prev : curr
          );
          const songObject = { songName: output.title, url: bestAudio.url };

          // push trimmed and lower cased song title.
          songNameArray.push(output.title.trim().toLowerCase());
          songs[output.title.trim().toLowerCase()] = {
            songName: output.title,
            url: bestAudio.url,
          };
        });
      } catch (error) {
        console.log("Error occur:", error);
        if (res.status === 403 && res.statusText === "quotaExceeded") {

       console.log("Limit Exceeded!")
        }
      }
    };
Enter fullscreen mode Exit fullscreen mode

Top comments (0)