Event Loop and Web Performance V2 Flashcards
List 3 microtasks
- Promises (resolving or rejecting)
- Mutation Observer callbacks
- process.nextTick() (Node.js)
List atleast 4 macrotasks
- setTimeout()
- setInterval()
- I/O operations (e.g. reading/writing files, making HTTP requests)
- UI rendering and user input handling
How does the event loop work in the context of this code snippet —-
console.log('Start'); setTimeout(() => console.log('Timeout'), 0); Promise.resolve().then(() => console.log('Promise')); console.log('End');
Here’s how the event loop works in this example:
- The initial synchronous task (console.log(‘Start’)) is executed and its output is printed to the console.
- The setTimeout() call is encountered and it schedules the “Timeout” callback to the macrotask queue. Since it’s a macrotask, it will be executed after all microtasks are processed.
- The Promise is encountered and it schedules its callback to the microtask queue. Since it’s a microtask, it will be executed before any macrotasks.
- The final synchronous task (console.log(‘End’)) is executed and its output is printed to the console.
- The microtask queue is checked and the Promise callback is executed, outputting “Promise”.
- The macrotask queue is checked and the “Timeout” callback is executed, outputting “Timeout”.
Explain the event loop in the context of the code snippet shown below —-
const fs = require('fs'); console.log('Start'); fs.readFile('data.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); console.log('End');
In this example, we use the fs.readFile() method to read the contents of a file asynchronously. The callback function is executed when the file has been read, and it outputs the contents of the file to the console.
Here’s how the event loop works in this example:
- The initial synchronous task (console.log(‘Start’)) is executed and its output is printed to the console.
- The fs.readFile() call is encountered and it schedules an I/O operation to read the file to the OS.
- The final synchronous task (console.log(‘End’)) is executed and its output is printed to the console.
- While the OS is reading the file, the event loop is free to handle other tasks.
- When the file has been read, the OS signals the event loop to execute the callback function with the file contents.
- The callback function is executed and its output is printed to the console.
main goal of the event loop ?
the event loop allows JavaScript to execute tasks asynchronously and handle I/O operations in a non-blocking way, improving performance and responsiveness.
explain the node js event loop in here —–
~~~
console.log(‘start’);
process.nextTick(() => {
console.log(‘next tick callback’);
});
console.log(‘end’);
~~~
In this example, we use the process.nextTick() function to defer the execution of a callback until the next iteration of the event loop. We also use the console.log() function to print messages to the console.
When we run this code in Node.js, the following happens:
- The message “start” is printed to the console.
- The process.nextTick() function is called, and the callback function is added to the “next tick queue”.
- The message “end” is printed to the console.
- The current iteration of the event loop finishes, and the “next tick queue” is processed.
- The callback function is executed, and the message “next tick callback” is printed to the console.
Note that the callback function is executed after all synchronous code has finished executing, even though it was scheduled before the “end” message was printed to the console.
purpose of next tick queue
The “next tick queue” is useful for ensuring that a callback is executed after all synchronous code has finished executing, without blocking the event loop.
key difference between the event loop in Node.js and the browser
One key difference between the event loop in Node.js and the browser is the addition of the “next tick” queue. This queue allows developers to schedule a callback function to run on the next iteration of the event loop, rather than waiting for the current task to finish. This can be useful for breaking up long-running operations or for ensuring that certain code runs before other code in the event loop.
purpose of google lighthouse
audit web pages for performance, accessibility, and other best practices.
What does a google lighthouse generated report contain ?
the report contains details in regards to performance, accessibility of a web page; it also contains recommendations for improving the quality of a web page.
Why would you use a PageSpeed Insights API client library ?
Before V8 hidden classes, how were object properties stored in javascript ?
JavaScript engines used dictionaries or hash maps to store object properties
What was the turning point in the JS story that led to the birth of V8 hidden classes ?
slower property access times in regards to dictionaries / hash maps
When would V8 classes be shared amongst two or more objects ?
If multiple objects share the same structure and have the same set of properties, they can share the same hidden class, improving memory efficiency.
purpose of using V8 hidden classes
faster execution times and improved overall performance of JavaScript applications.
purpose of browser cache ?
By using the browser cache, we can improve the performance of web pages by reducing the number of requests that need to be made to the server.
Where is the browser cache located ?
on the user’s device
Which API can be used to interact with the browser cache ?
Cache API
purpose of service workers ?
Service workers are scripts that run in the background of a web page, separate from the main thread of the browser. They allow you to cache resources and handle network requests, which can improve the performance and offline functionality of web pages
purpose of local storage ?
Data storage on a browser irrespective of the fact that the browser window / browser session would stay open.
purpose of indexed DB ?
IndexedDB is a client-side database API that allows web applications to store structured data locally, with indexed access.
meaning of asynchronous API
means that all database operations are non-blocking and use callbacks or promises to handle results
Is indexed DB synchronous or asynchronous ?
async
which are the 5 caching strategies in JS?
- Indexed DB
- Local storage
- session storage
- browser cache / HTTP cache
- service workers
what are worklets ? What would be some possible use cases ?
Worklets are a new type of JavaScript API that allow you to perform heavy computations and animations off the main thread of the browser.
Worklets can be used for a variety of tasks such as animations, audio processing, and more.
why should you use efficient data structures ?
Using efficient data structures can improve performance by reducing the amount of time it takes to access and manipulate data.
Name some efficient data structures in JS you can use
arrays
sets
maps
What is going on here ?
// HTML code <ul id="myList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> // JavaScript code const myList = document.getElementById('myList'); myList.addEventListener('click', function(event) { if (event.target.tagName === 'LI') { console.log('You clicked on ' + event.target.textContent); } });
event delegation
What is event delegation ?
Event delegation is a technique in JavaScript where you attach an event listener to a parent element instead of each individual child element. This is useful when you have a lot of child elements that need the same event listener, as it reduces the amount of code you need to write and can improve performance.
What is the purpose of using the for-loop in the code below ?
// create a document fragment const fragment = document.createDocumentFragment(); // add multiple elements to the fragment for (let i = 0; i < 10; i++) { const li = document.createElement('li'); li.textContent = 'Item ' + i; fragment.appendChild(li); } // append the fragment to the DOM document.getElementById('myList').appendChild(fragment);
A document fragment is a lightweight container that allows you to group multiple DOM operations together, which can improve performance by reducing the number of times the DOM is updated.
So the for-loop basically minimizes DOM manipulation
Why are we using map here ?
// create an array of items const items = ['Item 1', 'Item 2', 'Item 3']; // create a string of HTML markup const html = items.map(item => `<li>${item}</li>`).join(''); // append the HTML to the DOM document.getElementById('myList').innerHTML = html;
minimizing DOM manipulation
Use string concatenation or template literals to create HTML markup, and then append it to the DOM all at once. This can be faster than creating individual elements and appending them one at a time.
why should you Cache references to frequently accessed DOM elements ?
so you don’t need to search for them every time you need to manipulate them.
purpose of the following code snippet
const concat = require('concat-files'); const uglify = require('uglify-js'); concat(['file1.js', 'file2.js', 'file3.js'], 'combined.js', (err) => { if (err) throw err; const result = uglify.minify('combined.js'); console.log(result.code); });
you can combine multiple CSS and JavaScript files into a single file and then minify them to reduce the size of the file. This will help reduce the number of HTTP requests needed to load your webpage.
purpose of using a performance profiler ?
Use a performance profiler to identify bottlenecks in your code. Tools like Chrome DevTools or Firefox Developer Tools can help you identify slow functions, memory leaks, and other performance issues.
name a couple of perf profilers
chrome dev tools
firefox dev tools
purpose of lazy loading
Lazy loading is a technique where resources are loaded only when they’re needed, instead of all at once. This can improve performance by reducing the amount of time it takes to load the page.
if yo have the following code snippet in a js file of your web application, what could you do to make sure this function doesn’t block other tasks
function longRunningTask() { let result = 0; for (let i = 0; i < 100000000; i++) { result += i; } return result; }
you could use a web worker;
Web Workers are a way to run scripts in the background, separate from the main UI thread. This can improve performance by freeing up the UI thread to handle user interactions.
why should you avoid global variables ?
Global variables can slow down performance by increasing the amount of memory needed to store data and making it harder to optimize code.
enlist 3 ways of minimizing http requests
Combine files, use compression, and use caching to reduce the number of requests.
What is the garbage collector ?
In JavaScript, the Garbage Collector (GC) is a built-in mechanism that automatically manages memory allocation and deallocation for objects in the program. It ensures that objects that are no longer needed by the program are identified and removed from memory, freeing up space for new objects and preventing memory leaks.
What does the GC track ?
All objects and their references
What do you mean by reference counting approach for garbage collecting ?
This approach keeps track of the number of references to an object. When the reference count drops to zero, the object is no longer reachable and can be garbage collected.
What do you mean by incremental approach for garbage collecting ?
This approach breaks the garbage collection process into smaller, incremental steps to avoid freezing the program while the GC is running. It also allows the GC to release memory more frequently, reducing the overall memory footprint of the program.
What do you mean by generational approach for garbage collecting ?
This approach divides objects into “young” and “old” generations based on their age. Young objects are more likely to be garbage collected because they are short-lived and have a shorter reference chain. Old objects are less likely to be garbage collected because they have a longer reference chain and are more likely to be still in use.
What is Mark and Sweep ? Where is it mostly used ?
Mark and sweep is a garbage collection algorithm.
It is used in programming languages that have automatic memory management.
What is CRP ?
The process via which the browser converts the html, js and css code into the visual components of a web page.
What is the 1st CRP step ?
HTML PARSING - conversion of the HTML code ( received from the server into the browser ) to the DOM
What is the second CRP step?
CSS parsing: The browser also receives the CSS code and parses it into a Cascading Style Sheet Object Model (CSSOM).
What is the 3rd CRP step ?
Rendering tree construction: The browser combines the DOM and the CSSOM to create a rendering tree, which is a hierarchical representation of the visual components of the web page. The rendering tree contains all the nodes that need to be displayed on the screen, including text, images, and other elements.
What is the 4rth CRP step ?
Layout: The browser calculates the position and size of each node in the rendering tree, based on the CSS styles and layout rules. This process is known as layout, or reflow, and can be time-consuming, especially for complex web pages.
What is the 5th CRP step?
Painting: Finally, the browser paints the pixels of the web page on the screen, using the rendering tree and layout information as a guide. This process is known as painting, or rasterization, and involves drawing each element of the web page on the screen.
Enlist 3 techniques via which CRP can be optimized
To optimize the CRP, web developers can use techniques such as:
1. Minimizing the use of blocking resources, such as large images or JavaScript files, that can delay the parsing and rendering of the web page.
2. Using optimized CSS styles and layout rules to minimize the time and complexity of the layout and painting stages.
3. Using modern web development frameworks and tools that optimize the CRP, such as server-side rendering or lazy loading of resources.
What is LCP ?
Largest Contentful Paint (LCP): LCP measures the loading performance of a web page. Specifically, it measures the time it takes for the largest element on the page, such as an image or text block, to become visible to the user.
What is FID ?
First Input Delay (FID): FID measures the interactivity of a web page. Specifically, it measures the time it takes for the page to respond to the user’s first interaction, such as a click or tap.
What is CLS ?
Cumulative Layout Shift (CLS) measures the amount of unexpected layout shifts that occur during the page’s lifetime.
What are core web vitals ?
Perf metrics designated by google to analyze the overall performance of a web page
What are the 3 metrics measured via core web vitals ?
LCP, FID, CLS
Enlist 5 ways by which you can optimize core web vitals
- optimizing images and other resources for faster loading,
- reducing the number of requests made by the page, and
- optimizing the layout and design of the page to minimize unexpected shifts.
- using pageSpeed Insights
- use chrome dev tools
Enlist 7 causes for memory leaks in javascript
- Circular References: When objects reference each other in a circular fashion, without a clear path for garbage collection, they can become “locked” in memory and never be released.
- Unused Variables: Variables that are created but never used, or not properly disposed of, can accumulate in memory over time and cause memory leaks.
- Event Listeners: When event listeners are not properly removed, they can accumulate and cause memory leaks, especially in long-lived applications.
- Timers: Timers that are not properly cleared can continue to run even when they are no longer needed, leading to memory leaks.
- Closures: When functions create closures, they can hold on to references to variables and data that are no longer needed, causing memory leaks.
- Large Data Structures: Large data structures, such as arrays and maps, can consume a lot of memory and cause leaks if they are not properly managed.
- DOM Elements: DOM elements can cause memory leaks if they are not properly removed from the document or if they have circular references.