> Agents can also search and read this documentation through its [MCP server](https://www.jedjs.com/~gitbook/mcp).

# Introduction

Introduction to finding problems on your website or JavaScript back-end and some ways to fix them.

Here we will talk about many of the different performance problems that you may encounter in a JavaScript application. We will discuss front-end issues such as large file downloads, slow processing, and finding bugs. On the back-end we will discuss scaling across threads and servers using techniques like clustering and micro-services, writing asynchronous code, and dealing with sessions.

Most importantly we will be covering how to use data to identify performance issues that matter allowing you to choose what to ignore, what code to modify, and what just needs more hardware.


# Do we need to care about performance issues?

Why should we care about performance issues when technology is always giving us something new.

Picture a developer on a laptop plugging away at the code for a site. As he is testing out the site, everything is snappy. The occasional rebuild process when he makes some minor changes is even happening in only a few seconds. Why would have a reason to stop and think that his new web app is going to be so slow that it will be nearly unusable?

The difference between the development environment and the actual user experience brings to mind the saying attributed to about everyone (Yogi Berra, Albert Einstein, Richard Feynman, Benjamin Brewster, etc.):

> In theory there is no difference between theory and practice, while in practice there is.

So what is the difference between the theory of a developer and the practice of a user? Here a few items we will cover in more depth at a later time.

* Processor performance - Developers use high-performance desktops or laptops while most people use lower powered computers or a mobile device.
* Bandwidth - Running a server on your local machine and accessing it without even going over the network is incredibly fast and makes it easy to ignore that most people will use an internet connection often one that is not particularly fast.
* Data size - When developing an application you don't generally create enough sample data to represent the large data sets that some clients use.
* Load - If you have a large number of visitors to your site your server(s) will experience drastically different loading on bandwidth, processing power, memory usage, etc. then it does when a single developer can hope to provide.

&#x20;


# Deciding What To Optimize

When do we put the time into optimizing code versus going with it as is?

Over optimizing can be worse than under optimizing. The main problem with over optimizing is that your development time quickly escalates to where you are never delivering, but you can also suffer from making code harder to read and even reduce performance in some environments if optimizations are too specific. For front-end code, where it will run on different browsers it is of particular concern, different operating systems, and even different CPU architectures.

### Time Sink <a href="#time-sink" id="time-sink"></a>

Optimizing your code can take a significant time commitment. Spending hours debating the advantage of using a linked list or a binary tree over an array can be well worth it in some situations, but when you are only storing a handful of values, it just isn't worth it. Besides, when you are first building an application, there are many features that you can't be entirely sure to what extent they will be used.

When writing code, you should pay attention to creating performant code but you shouldn't obsess over it unless you are writing something that you already know has to be extremely performant, such as a library that will be used extensively in your application. Obsessing over performance comes after you have the code running.

No matter how well you think, you understand the problem space you should always plan on iterating. To decide what you need to optimize you need data. You don't have data until you have an application. Before then what have is ideas and assumption and what you need is data. The data will come from multiple sources, but without it, all of your optimization assumptions are just assumptions.

> **If we worked on the assumption that what is accepted as true really is true, then there would be little hope for advance. - Orville Wright**

### Code Complexity <a href="#code-complexity" id="code-complexity"></a>

Some code optimizations can make code easier to read and maintain, but more often it is far more complex. Complex code is harder to read, harder to isolate, and harder to test all of which makes it more expensive to maintain and more difficult for you to get new hires up to speed.

### Optimizations That Don't Span Environments <a href="#optimizations-that-dont-span-environments" id="optimizations-that-dont-span-environments"></a>

A question I have seen over and over in one form or another is:

> Which loop is faster?

On the surface, this seems like a valid question, after all, if we know the fastest loop why can't we use that everywhere?

Where the question breaks down is when you have different ways for a loop to be handled. So while Spidermonkey, the engine powering the JavaScript Mozilla Firefox, may process a `forEach` differently then V8, Google Chrome's JavaScript engine. Not only that but the implementation between versions of each JavaScript engine may and in some cases do handle the `forEach` differently. So now you have to compare the performance of each loop type in each of the many different JavaScript engines out there, and on top of that, you have to account for performance in different operating systems and the different CPU architecture of devices.

Not only that but what happens next week when you have a new version of one or other of the browsers? These kinds of optimizations are often problematic unless you can lock-down the environment where the code is running.


# Why Data?

Data drives most of the interactions on an application. So it makes sense that it should drive how we write the code behind the interactions.

Computers only understand data, that data may be in the form of instruction, something to store for later, or as something to process.

When we interact with a computer in any form, we do it for data. A simple example of this is when we use a calculator, or calculator application. In this case, we enter a number an operator (+, -, /, \*) and another number.

Some slightly more complicated examples could be to write or read an article where we transfer data from the writer to the reader, or when we watch a movie or play a game where someone added data in the form of images, sounds, or interactions for us to experience. The list goes on and includes anything we do to interact with a computer.

As a non-computer, we still mainly function on data. In fact, our ability to process data often puts computers to shame. We can take a few seemingly unrelated pieces of data and extrapolate wholly new concepts. While this is a fantastic ability, we often overuse this ability and ignore data that is available that would give us a more precise answer then we could come up without it.

Let me give you an obvious example. Take the following equations.

```
5 * 3 / (x + 2) = y
```

Now give me the value of y as a number. We obviously can't do that with any hope of a correct answer without knowing x. However, that is the kind of thing we can do much better than a computer. It will still be wrong but if it were on a multiple choice quiz in school we would still pick a number based on what kind of numbers x has been in previous questions and what seems like a reasonable answer at least has a chance of being right and so is better then a definite wrong answer.

When we are writing our code, we often make assumptions about how they will be used and don't take the time to figure out what x is.

> ## Assumptions are unopened windows that foolish birds fly into, and their broken bodies are evidence gathered too late. - Bryan Davis


# What Types of Data Do I Need?

If we accept that our optimization decisions should be made based on data then what kind of data will we use?

When told to pick three apples from a tree you do not need to factor in that a volcano is erupting a couple of thousand miles away. In the same vane, there are a lot of different types and sources of data we could use when optimizing. However, the real question is "What is it that really matters?"

To start with there are different answers for different web applications depending on how your system is setup.&#x20;

### Front-end Data Collection

On the front-end, our browser is our most significant friend. Modern browsers allow everything from watching traffic to and from your computer for the website to how long it is spending processing individual functions in the code. They also provide throttling options to limit bandwidth and processor performance to give you an idea of what it will feel like for visitors with lower performing hardware.

To see front-end performance out in the wild there are third-party services that can be setup to monitor front-end performance and how users interact with your site. Tracking front-end performance could be useful if you are encountering isolated situations where only a few users are experiencing slow-downs, but they are hard to replicate on your own devices.

Tracking how users interact with your site is essential to making the right performance decisions. If there is one area of your application that tends to get the bulk of the site usage that might be the right place to focus on tweaks to performance. There is more to it than just working where the traffic is as other areas could be getting avoided because of how slow they are.

For the front-end, we can often get side-tracked into graphic design issues. These are important in their own right, but they aren't part of performance issues. If you are a small team running the entire project it can be easy to see something that you don't like and spend your time on that and lose focus on improving your performance. If you are responsible for graphic design, make a to do for it and deal with it later, if you aren't accountable make a to do and then report it later.

### Back-end Data Collection

On the back-end, we don't have a single tool that provides all the answers. It is also an area where there can be a significant number of things slowing you down. However, for measuring performance, it is relatively easy to see if you have a problem. You merely need to know how long it takes from request to response. Measuring timing can even be as simple as logging some metrics to the console or a log file.

There are many more things that can be analyzed that are just conditions or causes of that initial measurement. Some additional considerations could include:

* Server load
* Database speed
* Third-party API calls
* Authenticating a request

The list goes on and on, but that is enough for now.

### Feedback

One more data source you should never ignore, and ultimately the most valuable of all data, is what your users feel while on the site. There are some technical ways to collect data, eye-tracking, mouse tracking, etc. Those can be helpful but ultimately just providing a feedback link on the page, getting beta testers to try it out and provide feedback, or sending out a survey are all ways to find out areas of the application that is annoyingly slow.

One warning here is that performance isn't often something people think of when they are trying out an application unless it is ridiculously slow. It is as users use the it that those performance issues start to annoy most users. So make sure when you are asking for feedback to ask them specifically about performance.


# User Analytics

What user analytics do we want to use to help with determining where to improve application performance?

When looking at user analytics, there are thousands of data points we can use. User analytics are generally intended for the marketing department, and we are only going to look into them for a couple of fundamental metrics. Even at that these aren't always going to be extremely clear on their performance implications

### Page Views

First, the most helpful metric is the number of times someone uses a page. As mentioned earlier, by evaluating page views you will get a sense of where inside the application people are going. If you know where users are going, you get an idea of how important it is that a page should be optimized. If the landing page is viewed five times as often as any other page, it makes sense that it is worth spending extra-time on optimizing it.

There are other ways to take advantage of page views. These different ways require a deeper understanding of your application and its flow, but they can indicate potential issues which are occasionally related to performance.

So the idea is to look and see if there are sections of the site where people are expected to go but don't seem to be. Remember to take care with this approach as more often then not there is something else keeping them from the page, such not seeing the link or not understanding why they should be going to the page.

### Exits

Exits are a pretty simple metric. It is the location where your users are leaving the application. With the exits statistic, you need to know where people should be exiting your application and you look for pages where they exit unexpectedly.

There will always be some exits from any page. Unlike, developers crazy about efficiency other people have lives that occasionally intrude on their use of an application. However, if there is anywhere, that seems to be higher then expected we can look to see if a performance issue is frustrating users, again this could be any number of the other problems so use it as a starting point and as validation that there may be something worth fixing.

Another thing to keep in mind is that if the exits are happening from a multi-step process, the major problem could have been from an earlier step, in particular, check the immediately proceeding step.


# The Browser - Loading

Modern browsers have built-in features that provide many resources for finding useful performance data.

The data from analytics or feedback from users helps us know what needs to be improved but it only helps you know where to point the microscope it isn't the microscope. Using the browser, we can get concrete performance data.

### The Network Tab

In browser developer tools there is often a network tab. This tab is an excellent place to see how the back-end is performing, to see how big the download is, and what your load time is.

#### Download Size

Getting the download size is the easy one to do. First, ensure your network tab is open and then either refresh the page or navigate to a new page if that is what you are testing. Typically there will be a size column for each request and a total download size for the site.

Large downloads can have a significant impact on the initial load times. Large download size is especially apparent on slower connections so if you have users in rural areas or on mobile devices track this with care.

#### Load Time

Load time is the time it takes from when your browser tries finding the URL to when it has finished downloading the content for the page.

Like download size, there usually is a column for this and a total for the site. Load time is closely related to the download size and so don't be surprised to see a correlation. However, if you look at the timing for each request, you will see that other factors affect the load time. So we should check both and pay particular attention to anything that doesn't seem to be related to the download size.

#### Time To First Byte

If you look at the timing for a request, you will see a field labeled either "Waiting" or "TTFB". TTFB stands for Time To First Byte and is an indication of how long the browser has to wait from when it sends a request to the server before the server starts replying.

TTFB is the metric you use to see how the back-end is performing.&#x20;

When the server receives the request, the server immediately begins fulfilling it. The server runs all the code that is needed for the request and makes any required calls databases, external APIs, files on the server, or other servers, all of which take time. So if you see a long TTFB on your requests, especially your XMLHttpRequests(XHR)s, then you may want to look at your back-end code or see if you can reduce calls to the database or external APIs.

There will be some time spent waiting for the request to reach the server and then some time spent waiting for the first packet to come back to the browser.

There are two places to check for load time gained outside of the server. The first is, tied to inefficiencies in your's and your user's infrastructure. For this reason, it makes a significant difference on how your load balancers are setup and what you use for a load balancer since every millisecond you lose is a loss to every request.

In addition to infrastructure, there is the actual distance between the server and the browser, the speed of light can be such a drag at times. If you have static files that are taking a while to load consider looking into a content delivery network (CDN). CDNs provide multiple locations and highly optimized hardware and software to reduce the TTFB for them.


# The Browser - Profiling on the Processing Tab

Once everything has been loaded your browser still has to figure out what to do with it all.

Front-end JavaScript processing is the area that you probably think of when you think of JavaScript performance optimization. Though for now, we are still focusing on finding where performance is a problem and.

### The Performance Tab

To investigate time spent processing we are going to use the Performance tab in the browser developer tools. One thing that is different about the performance tab from the network tab is that you have to tell the browser specifically when you want to start recording performance data and when to stop.

The reason you have to start and stop recording performance data by hand is that it requires a lot of memory and processing power to make detailed measurements. Since by now you should have used other resources to find specific points you want to measure this isn't an issue as you have a general idea of where to start and where to stop.

You will probably either measure the processing that is required when the application is first loaded, after all getting the data is only part of the battle, or record a specific action that has been found to be costly.

#### Call Tree

The first place to check it the Call Tree View. The call tree will show you how many times discrete functions get called. Additionally, it shows the time spent running the function and the percent of the total processing that went into each function.

One nice feature that browsers offer now is the ability to see a time chart showing how much processing is happening when and allow you to select a specific slice of time for which you are analyzing.

#### Flame Chart (in Chrome this is the Main chart)

The Flame Chart is pretty amazing. It provides a graphical view of each function and what each function calls. The flame chart is helpful in that while function x on the surface may look like a culprit it could be a different function that needs to be optimized. It could be that function x calls function y unnecessarily (function x is above function y), and so it is function x that needs to be optimized. The reverse could also be true, and function j may call function z and function z is not performing as desired so it should be the one to focus on when doing your optimizations.

As with the call tree, you can zoom into the Flame Chart to see what is going on at a specific time and it helps you (based on function names) to identify when exactly the action you are trying to track happened.


# The Browser - Throttling

Throttling is useful for finding general performance issues.

Once you have seen what it takes to load the page on your development machine, you should check again with the worst equipment/connection your users are likely to use. So need to know something about your target users.&#x20;

### Determining Target Users&#x20;

If you don't know who your target audience is then someone else in your company should, I would recommend talking to your marketing department for a start. If nobody knows your target audience, I would suggest figuring that out. Performance optimization is only one aspect where knowing your target audience is vital.&#x20;

Finding your target audience is a vast subject, and there are whole books written on the subject. We won't go into that level of detail, but we will add some additional concepts that may not be part of the standard audience description.&#x20;

Some simple questions you should think about to get started:&#x20;

* What is it your application offers?
* Who could benefit from your application?
* Why would someone want to use your application?
* Are there certain individuals or companies who would benefit the most from your application?
* Are there current users of your application whom you know?&#x20;

Typically you will want to create three or more fictional individuals. Give each of them a name, specific age, gender, set of interests, job, and anything else you can think of that make them feel like they could be a real person.&#x20;

Once you have a few members of your target audience, you will need some additional information about them. The things you will want to identify are, what devices do they use to connect to the application, desktop, laptop, tablet, phone. Try to be as specific as possible. Do they use a budget phone? Do they use the latest flagship phone from one of the several mobile phone companies? Or are they somewhere in the middle?&#x20;

Then determine how they connect to the internet. Is it over a lightning fast fiber connection from their office? Over a slower but still high-speed cable or DSL connection they can get in larger cities? Or is it a slower DSL connection from a smaller town or a somewhat rural location? Or do they live off the grid and use satellite for internet? Or if they are connecting through their phone how is their connection 4G, 3G, 2G, or spotty and extremely slow?

You also need to understand how they will react to different types of performance issues. Will slow loading time be a more significant issue? Or will slow navigation?&#x20;

### Throttling Your Browser

Once you know who your target is you are ready to try out your application as if you were one of them. There are two types of throttling we can do, and I would recommend doing both of them. There is bandwidth throttling and CPU throttling.&#x20;

#### Bandwidth Throttling

Typically the easiest to find is the bandwidth throttling. It is generally located on the network tab or in the mobile design mode. There will be several good options to get you started but if you want to replicate something like satellite you will need to create a custom profile to account for satellites greater latency.

#### CPU Throttling

CPU throttling isn't as generally available, but it is available in Chrome Dev Tools. It is located on the Performance tab when you change the capture settings. The options for CPU throttling are much more limited than for bandwidth throttling, but you can reduce your processor's performance to give you a better idea of how your application performs.

#### Using Throttling

Once you set your throttling settings, you will rerun your tests on the problem areas and over the whole application to find areas where the performance will cause issues for your users.


# The Browser - Memory Usage

How does memory usage affect performance?

Memory usage may not seem like a big deal with performance. In fact, often speed optimizations com at the cost of increased memory storage using techniques like caching. However, it is still essential for a couple of reasons.&#x20;

First, it takes time to initialize the data and if there is little chance that you will need it, or if you only need a small part of the data then making some small changes can provide a performance boost.&#x20;

Second, if the computer running the code is running low on memory, you are going to see a degradation of performance as the JavaScript engine is running its garbage collection processes more and more frequently. Running low on memory is most often the problem encountered when there is a memory leak in your program.&#x20;

### Memory tab

The main thing to check on this tab is a snapshot of the memory used. This snapshot of is of the memory heap and contains all the objects in the application which were in memory at the time the snapshot was taken.&#x20;

With the snapshot, you can drill down into the more significant sections of memory use and find potential items that can be reduced or removed.&#x20;

If you take multiple snapshots, you can compare them which is helpful when you are looking for memory leaks.


# The Server

How is the server performing?

### Start With the Browser

The browser is one of the best tools for seeing how the overall application is working but when we look at JavaScript running on the server, it seems that the browser shouldn't be of much help.

Browsers do give us some information. In particular, we discussed TTFB or Time To First Byte earlier. TTFB is mostly a measure of server performance, and if it is more then about half a second, something should be done to speed up the server.

All the browser lets us see about the server's performance is what endpoints are slow. Knowing which API endpoints or pages are slow gives us a place to start looking for what is causing the slowdown.

### General Server Statistics

Another place we should start looking for performance bottlenecks is by looking at general server statistics. CPU usage, memory usage, and bandwidth usage are all areas to track.

In particular when checking CPU usage and memory usage you should review individual applications, such as NodeJS or any other application that may be consuming a significant portion of your processing power or memory usage.

### Check Databases and Other External Sources

If the server uses a database or accesses another server, you will want to check how those are performing as well.


# Profiling Your Code On The Server

Finding bottlenecks in your JavaScript code run in NodeJS.

There are a large number of third-party code profiling tools for NodeJS. You should consider looking into some of those if you are having a hard time identifying slowdowns. Especially if you have real-world users who are having server performance issues, but you can't replicate them in your development environment.

For many of your profiling needs, you can use the same V8 profiler that is part of the V8 engine used in Chrome. As with profiling your process performance on the browser you only run this for a limited time, and you shouldn't run this on your production server.

### Start Profiler

To run node with the profiler enabled then add the following tag to the command line.

```
--prof
```

So your command to run the server will look something like

```
node --prof index.js
```

After you run the command, you will want to repeatedly access each of the endpoints you are trying to profile. Accessing the URL of the endpoints can be done in several ways.

### Access Endpoints

You could use the application and manually go to the parts that will call the URL. Utilizing the application front-end can be slow and unfocused, especially if you have to refresh the page where it will almost always make several additional requests to other endpoints.

Another option is to use a tool like Postman(<https://www.getpostman.com/>) or curl(built-in or easy to install on most \*nix based OS's) that lets you access an endpoint directly. Postman can be especially helpful if you have to be authenticated to access the endpoint.

Then there are tools specifically designed for load testing a server such as ApacheBench(<https://httpd.apache.org/docs/2.4/programs/ab.html>) or Seige(<https://www.joedog.org/siege-home/>). These have the advantage of pushing the server with lots of traffic and less overall work for you in most cases. With ApacheBench you can include request headers, which allows you to pass authentication information.

### Review Results

After accessing the endpoint, you are testing stop your server.

You will now have a file labeled something like:

```
isolate-0xXXXXXXXXXXXX-v8.log
```

This file isn't useful to us as is. To make it readable, we will need to process it. Processing can be done using NodeJS with the following flag:

```
--prof-process
```

This flag requires you pass in the filename and prints a human-readable version of the file. So you may want to pipe the results to another file using a command such as:

```
node --prof-process isolate-0xXXXXXXXXXXXX-v8.log > endpoint-name.profile.txt
```

In there we can see what it is that is using up your CPU processing time.


# Using Profiling Data - NodeJS

Now that you have data you have to start using it.

If your profiling data comes from NodeJS, you will have sections contained in square brackets \[] that you will look for.

First, check out the summary to see what type of code (JavaScript, GC - Garbage Collection, C++, etc.) is using up the highest percentage of processing power.

Second, look at the section for the type of code that is using the most processing power. Here you will look for functions that seem to be using more than their share. Looking through the summary sections will give you a starting point to filter through your profiling in NodeJS.

### Bottom Up

Once you have some profiling data and have some idea of where to look, whether from the steps above for NodeJS or from using something like the flame chart from the section on profiling in the browser, the next step is to figure out what is calling those slow processes and see if we can make some changes.

To find the problem functions use the Bottom Up chart in the browser dev tools or the \[Bottom up (heavy) profile] section from the processed profile file for NodeJS. The first step is to start on the top of the chart and find the parent function that seems to be related to a problem.

Insert image here-----------------------------------------------------------

In the above image from NodeJS, you will see that there are several functions in indenting rows that show the ticks or ms, the parent percentage, and the name.

The ticks are a measure of CPU processing time used internally to the OS. Ticks are an absolute measure of the time the CPU was running, and is used in NodeJS and is an equivalent measure to the milliseconds used in browsers developer tools.

The parent percent is a relative percentage. It is the percentage of times the current function ran where it called the parent. Except for the first row which shows the percentage of total calls to the application for which that function is called.

The name is self-explanatory as it indicates the name of the function and where it is in the code.

The keys we are looking for here are what is calling the expensive processes. If we have a reasonably straight path, one where the parent percentage is 100% or close, then we should start at the deepest point where it is close to 100% and then see if you can make any changes to that function to reduce the calls to the higher function. You will want to follow that up as high as you can looking for ways to reduce usage of the higher function.

It could also be that the path is pretty branched, in this case, you probably want to start as high on the tree as you can and see if you can make internal improvements to performance and then work your way down.


# Optimization Concepts

How to optimize your application using specific optimization concepts or techniques.

Earlier we discussed finding performance issues now we ready to start fixing them. To help you find the most useful optimizations for the items you have already identified the following section will be written more as a reference and organized into several categories.

### Overall Application Structure (or Communication)

If the problem seems to be broad and not limited to individual functions or loops, then this might be the place to look. These optimization concepts will be related to the overall structure of your application or a subset of your application. There will be a strong emphasis on communication and messaging techniques here as large systemic problems usually are techniques related to how different parts of the system communicate.

### Structures and Algorithms

We will not have all the structures and algorithms here as there are many excellent books on the subject but we will discuss the basics and some that are particularly useful in JavaScript.

### JavaScript

JavaScript is a scripting language that is compiled by the JavaScript engine before running and knowing how modern JavaScript engines do their optimizations will let us optimize our code to make the engines more efficient.

### Browser

While JavaScript has its specifics, the way browsers implement JavaScript adds some additional areas where we want to be aware of in our optimizations.


# Overall Application Structure (or Communication)

Solutions for systemic problems

Often performance bottlenecks are caused by your system architecture instead of something specific to a single function or storage structure.

Often performance concerns are related to communications. Communications arguably could cover everything in your application as there is always some level of communication in every process. However, this section will deal with general communication concepts and other architectural concerns.


# Structures and Algorithms

Basic computer science concepts.

Structures and algorithms is a discipline that has many books written on the subject and is covered extensively in computer science classes at universities. The following section will not be an extensive treatise on the topic but will briefly cover some of the broad concepts and some specifics for structures and algorithms in JavaScript.


# JavaScript

JavaScript specific performance techniques.

Being an asynchronous event-driven programming language JavaScript has some unique challenges and opportunities when writing fast, efficient code. Additionally, JavaScript itself has some unique coding functionality that makes optimization of the application require a different mindset.


# Browsers

Browsers create unique optimization challenges.

Interacting with browsers creates additional challenges for the JavaScript developer. The primary considerations relate to accessing the DOM, animations, locking the user interface, and loading remote JavaScript.


