Javascript/8 JavaScript Performance Tips I Discovered After Years of Coding.md
... ...
@@ -0,0 +1,265 @@
1
+https://medium.com/no-nonsense-backend/8-javascript-performance-tips-i-discovered-after-years-of-coding-56ab5fae43af
2
+
3
+# 8 JavaScript Performance Tips I Discovered After Years of Coding | by Yash | No Nonsense Backend | Dec, 2024 | Medium
4
+
5
+![Yash](https://miro.medium.com/v2/resize:fill:88:88/1*H9qc5tPYZg_qG6qb9ToUtA.jpeg)
6
+[Yash](https://medium.com/@yashwanthnandam)
7
+
8
+
9
+![No Nonsense Backend](https://miro.medium.com/v2/resize:fill:48:48/1*ezv2ukKythNsMZGWUybDHA.png)
10
+[No Nonsense Backend](https://medium.com/no-nonsense-backend)
11
+
12
+javascript
13
+
14
+Hey Everyone!! I wanted to share these Javascript Performance tips, that i feel that everyone should be aware of, since it took a lot of effort and mistakes for me to learn it. So, here are eight performance tips that have made a real difference in my projects. Dont forget to bookmark them for further reference.
15
+
16
+1) Use Strict Mode
17
+------------------
18
+
19
+Enabling strict mode in JavaScript catches common coding bloopers, prevents the use of undeclared variables, and makes your code run faster.
20
+
21
+**How to Enable Strict Mode:**
22
+
23
+```
24
+"use strict";
25
+function myFunction() {
26
+ // Your code here
27
+}
28
+```
29
+
30
+
31
+“use strict;” can tell the browser to execute in strict mode, which can improve the performance
32
+
33
+2) Minimize DOM Manipulation
34
+----------------------------
35
+
36
+Manipulating the Document Object Model (DOM) is one of the slowest operations in JavaScript. Reducing the number of direct DOM manipulations can significantly improve performance.
37
+
38
+**Instead of:**
39
+
40
+```
41
+const list = document.getElementById('myList');
42
+const items = ['Item 1', 'Item 2', 'Item 3'];
43
+items.forEach(item => {
44
+ const li = document.createElement('li');
45
+ li.textContent = item;
46
+ list.appendChild(li);
47
+});
48
+```
49
+
50
+
51
+**Use Document Fragments:**
52
+
53
+```
54
+const list = document.getElementById('myList');
55
+const items = ['Item 1', 'Item 2', 'Item 3'];
56
+const fragment = document.createDocumentFragment();
57
+```
58
+
59
+
60
+By using a document fragment, you batch your DOM updates, which is much more efficient.
61
+
62
+**Personal Note:** After switching to document fragments in a dynamic list, I noticed a significant reduction in rendering time, especially with large datasets.
63
+
64
+3) Use Event Delegation
65
+-----------------------
66
+
67
+Attaching event listeners to multiple DOM elements can be inefficient. Event delegation allows you to handle events at a higher level in the DOM.
68
+
69
+**Instead of:**
70
+
71
+```
72
+const buttons = document.querySelectorAll('.myButton');
73
+buttons.forEach(button => {
74
+ button.addEventListener('click', function() {
75
+ // Handle click
76
+ });
77
+});
78
+```
79
+
80
+
81
+**Use Event Delegation:**
82
+
83
+```
84
+document.body.addEventListener('click', function(event) {
85
+ if (event.target.classList.contains('myButton')) {
86
+ // Handle click
87
+ }
88
+});
89
+```
90
+
91
+
92
+This way, you attach a single event listener to a parent element, reducing memory usage and improving performance.
93
+
94
+**Personal Note:** Implementing event delegation cleaned up my code and made it more maintainable, especially when dynamically adding new elements.
95
+
96
+4) Avoid Memory Leaks
97
+---------------------
98
+
99
+Memory leaks can slow down or even crash your application. Be mindful of closures and unnecessary references that prevent garbage collection.
100
+
101
+**Common Pitfall:**
102
+
103
+```
104
+let element = document.getElementById('myElement');
105
+element.addEventListener('click', function() {
106
+ console.log('Clicked!');
107
+});
108
+// Later in the code
109
+element = null; // This doesn't remove the event listener
110
+```
111
+
112
+
113
+**Proper Cleanup:**
114
+
115
+```
116
+let element = document.getElementById('myElement');
117
+function handleClick() {
118
+ console.log('Clicked!');
119
+}
120
+element.addEventListener('click', handleClick);
121
+// Later in the code
122
+element.removeEventListener('click', handleClick);
123
+element = null;
124
+```
125
+
126
+
127
+By removing event listeners when they are no longer needed, you prevent memory leaks.
128
+
129
+**Personal Note:** After noticing my app slowing down over time, I realized I wasn’t properly cleaning up event listeners. Fixing this improved performance dramatically.
130
+
131
+5) Optimize Loops
132
+-----------------
133
+
134
+Loops can be performance bottlenecks. Simple changes can make them more efficient.
135
+
136
+**Instead of:**
137
+
138
+```
139
+for (let i = 0; i < array.length; i++) {
140
+ // Do something with array[i]
141
+}
142
+```
143
+
144
+
145
+**Cache the Length:**
146
+
147
+```
148
+for (let i = 0, len = array.length; i < len; i++) {
149
+ // Do something with array[i]
150
+}
151
+```
152
+
153
+
154
+Or use modern methods like `for...of` or array methods like `forEach`, which are optimized.
155
+
156
+**Personal Note:** In a performance-critical application, caching the array length in loops reduced execution time noticeably.
157
+
158
+6) Debounce and Throttle Expensive Functions
159
+--------------------------------------------
160
+
161
+For functions that are called frequently, like window resizing or scrolling, use debouncing or throttling to limit how often they run.
162
+
163
+**Debounce Example:**
164
+
165
+```
166
+function debounce(func, delay) {
167
+ let timeout;
168
+ return function() {
169
+ clearTimeout(timeout);
170
+ timeout = setTimeout(func, delay);
171
+ }
172
+}
173
+window.addEventListener('resize', debounce(function() {
174
+ // Handle resize
175
+}, 250));
176
+```
177
+
178
+
179
+**Throttle Example:**
180
+
181
+```
182
+function throttle(func, limit) {
183
+ let inThrottle;
184
+ return function() {
185
+ if (!inThrottle) {
186
+ func();
187
+ inThrottle = true;
188
+ setTimeout(() => inThrottle = false, limit);
189
+ }
190
+ }
191
+}
192
+window.addEventListener('scroll', throttle(function() {
193
+ // Handle scroll
194
+}, 250));
195
+```
196
+
197
+
198
+**Personal Note:** Implementing debounce on a window resize event handler fixed a lag issue in my UI, making it feel much more responsive.
199
+
200
+7) Use Asynchronous Code Wisely
201
+-------------------------------
202
+
203
+Non-blocking code keeps your application responsive. Use asynchronous programming features like `async/await` and Promises.
204
+
205
+**Example:**
206
+
207
+```
208
+async function fetchData() {
209
+ try {
210
+ const response = await fetch('https://api.example.com/data');
211
+ const data = await response.json();
212
+ // Process data
213
+ } catch (error) {
214
+ console.error(error);
215
+ }
216
+}
217
+```
218
+
219
+
220
+By handling operations asynchronously, you prevent blocking the main thread.
221
+
222
+**Personal Note:** Switching to `async/await` made my code cleaner and improved performance by not blocking the UI during data fetching.
223
+
224
+8) Leverage Browser Caching
225
+---------------------------
226
+
227
+Caching assets can greatly improve load times. Set appropriate cache headers on your server and use service workers for advanced caching.
228
+
229
+**Service Worker Example:**
230
+
231
+```
232
+self.addEventListener('install', function(event) {
233
+ event.waitUntil(
234
+ caches.open('v1').then(function(cache) {
235
+ return cache.addAll([
236
+ '/index.html',
237
+ '/styles.css',
238
+ '/script.js',
239
+ ]);
240
+ })
241
+ );
242
+});
243
+```
244
+
245
+
246
+By caching static assets, you reduce network requests and improve performance.
247
+
248
+**Personal Note:** After implementing service workers, my web app loaded almost instantly on subsequent visits, enhancing the user experience.
249
+
250
+Wrapping Up
251
+-----------
252
+
253
+**Final Thoughts:**
254
+
255
+* **Test After Changes:** Always benchmark your application before and after optimizations to ensure they’re effective.
256
+* **Stay Updated:** JavaScript and web technologies evolve rapidly. Keep learning to take advantage of new features and best practices.
257
+
258
+If you have any JavaScript performance tips or tricks, please share them in the comments below!
259
+
260
+**Happy coding!**
261
+
262
+**Thanks for sticking with me till the end! If you enjoyed this content and want to support my work, the best ways are:**
263
+
264
+* **Follow me here on Medium.**
265
+* **Connect with me on** [**LinkedIn**](#)**.**
... ...
\ No newline at end of file