6 Cool Javascript Features to Make Your App High-Performing
Let’s get a bit techy today with increasing app performance. Javascript wasn’t a high-performing language in the beginning but now we have techniques to optimize web applications. Users are not patient nowadays, so more than 3 seconds is too much to wait for page downloading.?
Tried and true features/techniques every #JS application will benefit from:?
Debouncing and throttling
Debouncing and throttling are great techniques to optimize event handling in web applications. Sometimes, we have too much firing of events, so the app struggles with speed. Both of the techniques improve performance but have different use cases.
Debouncing puts off the execution of a function until a certain period of time has passed without the event being triggered again. It’s impressive when you want to avoid multiple executions of the function. It is highly useful for search box suggestions, text-field auto-saves, and eliminating double-button clicks.
Throttling restricts the number of times a function may be run in a given amount of time. This proves useful when you want to prevent overmuch execution of a function. If the code is repeated a lot of times, throttling improves the speed of online apps.
A great technique for user events like resizing and scrolling.?
Example of debouncing:
function debounce(func, timeout)
? let timer;
? return (...args) => {
? ? clearTimeout(timer);
? ? timer = setTimeout(() => { func.apply(this, args); }, timeout);
? };
}
function saveInput(){
? console.log('Saving data');
}
const processChange = debounce(() => saveInput(), 300);{
Example of throttling:
function throttle(func, limit)
? let lastFunc;
? let lastRan;
? return function(...args) {
? ? if (!lastRan) {
? ? ? func.apply(this, args);
? ? ? lastRan = Date.now();
? ? } else {
? ? ? clearTimeout(lastFunc);
? ? ? lastFunc = setTimeout(() => {
? ? ? ? if ((Date.now() - lastRan) >= limit) {
? ? ? ? ? func.apply(this, args);
? ? ? ? ? lastRan = Date.now();
? ? ? ? }
? ? ? }, limit - (Date.now() - lastRan));
? ? }
? };
}
function checkStatus(){
? console.log('Check status');
}
const processChange = throttle(() => checkStatus(), 1000);{
Web Workers
Web Workers is a feature that allows running JavaScript code in a separate thread. It is useful if you want to perform heavy computations or long-running tasks without blocking the main thread. It helps to take some CPU-intensive work from the main thread.
For instance, you need to analyze video or audio data, or cache data for later use, or update many rows of a local web database.?
// main.js
// create a new web worker
const worker = new Worker('worker.js');
// send a message to the worker
worker.postMessage('Hello from the main thread!');
// listen for messages from the worker
worker.onmessage = (event) => {
? console.log(`Message from worker: ${event.data}`);
};
// worker.js
// listen for messages from the main thread
.
onmessage = (event) => {
? console.log(`Message from main thread: ${event.data}`);
? // send a message back to the main thread
postMessage('Hello from the worker thread!');
};s
Memoization
Memoization is a technique that helps optimize function calls by caching the results of expensive function calls. In simpler terms, if some function calls are repetitive memoization helps store them in cache and use less effort to get them when needed. By reducing the number of function calls, the application performance gets tons better.??
领英推荐
function memoize(func)
? const cache = {};
? return function(...args) {
? ? const key = JSON.stringify(args);
? ? if (cache[key]) {
? ? ? return cache[key];
? ? }
? ? const result = func.apply(this, args);
? ? cache[key] = result;
? ? return result;
? };
}
function expensiveFunction(x, y) {
? console.log("Calculating...");
? return x + y;
}
const memoizedFunction = memoize(expensiveFunction);{
Tree shaking
Tree shaking is a technique that removes unused code from JavaScript modules. This can reduce the size of the JavaScript bundle thus improving the app performance.
// math.js
export function add(a, b) {
? return a + b;
}
export function subtract(a, b) {
? return a - b;
}
// app.js
import { add } from "./math.js";
console.log(add(1, 2));s
In this example, we have two functions exporting from the math.js module. However, in the app.js module we are only importing one function. When we bundle the application using tools like Webpack, the unused functions will be removed from the bundle. Sometimes, it’s called removing the dead code.?
Caching
You probably know about this one, it’s not new. A technique that helps to store frequently accessed data in the browser's cache memory. Basically, we reduce the number of requests sent to the server, thus speeding up the app. JavaScript caching uses local storage, session storage, or cookies.?
Example:
function getData()
? const dataKey = 'myData';
? // Check if data is present in local storage
? const cachedData = localStorage.getItem(dataKey);
? if (cachedData) {
? ? console.log('Retrieved data from cache.');
? ? return JSON.parse(cachedData);
? }
? // If data is not present in local storage, fetch it from server
? fetch('https://api.example.com/data')
? ? .then(response => response.json())
? ? .then(data => {
? ? ? console.log('Fetched data from server.');
? ? ? // Store data in local storage
? ? ? localStorage.setItem(dataKey, JSON.stringify(data));
? ? ? return data;
? ? })
? ? .catch(error => {
? ? ? console.log(error);
? ? });
}
// Call the function to fetch data
const myData = getData();{
Async/Await
Async/await feature in JS lets developers write #asynchronous code in a synchronous way. This feature can really improve the app's performance by reducing the blocking of the main thread (which does most of the heavy lifting). Async/await can be used to handle network requests, file I/O, and other time-consuming tasks.?
Example:
async function fetchUser(userId)
? try {
? ? const response = await fetch(`https://api.example.com/users/${userId}`);
? ? const user = await response.json();
? ? return user;
? } catch (error) {
? ? console.log(error);
? }
}{
#Javascript features and techniques are useful in optimizing application #performance. After all, no one likes slow websites and #apps. Better code - better speed - better user satisfaction with your product. Using the mentioned ways above in Javascript #code will benefit the app and its end users.?
More tech advice on my Hackernoon and our website.
Happy coding!