This blog post shows additional optimizations for JavaScript developers from my own experiences.
Another micro optimizations in JavaScript
In this blog post we look into the micro optimizations of JavaScript code. These optimizations can improve performance in some specific cases.
Sorting of arrays
In some cases it's better to sort an array of strings only by first 3 characters. I use the optimization bellow in Total.js framework:
Sorting of UTF8 characters is much faster by using the above method because we can't sort UTF8 chars (e.g. Slovak characters ľščťžýáíé
) in JavaScript easily and a better solution is to remove diacritics from the string and sort it afterwards (of course, sorting can be strict, but wherever possible using this will improve performance). Total.js framework implements quicksort
algorithm which is faster than built-in Array.sort()
- I haven't had any problems with it so far.
Null and Undefined
I often use bellow if statement:
if (value !== undefined && value !== null)
it can be replaced with simpler version:
if (value != null)
Regullar expressions
If you only use string.match()
for verification whether the string
contains some value or not then it's better to use regexp.test(string)
than string.match()
from performance point of view:
Be careful when you use regexp.test()
and global modificator /g
:
Unfortunately it happened to me and it was very difficult to find the bug, that's why i mentioned it. So be careful about it. I have one tip for Regular Expressions, cache them and you will increase a performance:
Order in comparisons
The order in comparisons is important and can increase performance of your applications, example:
My recommendation for comparisons:
If it's possible start with simple data types boolean
, interger
, string
in your conditions then proceed with easiest comparisons to the most cpu intensive comparisons.
Other posts from Total.js Platform
- 2024-11-13Benchmarking Node.js Frameworks: selecting your framework for 2025!
- 2024-11-01October report 2024
- 2024-10-22Performance Testing: Total.js vs. NestJS
- 2024-10-01September report 2024
- 2024-09-27Total.js UI Builder: #2 designing your first interface
- 2024-09-26Total.js V5: Middlewares
- 2024-09-23Beginner Guide to Total.js UI: # 05 Client-side routing
- 2024-09-23Total.js UI #4: Data Binding (Part 2 – Practical Example)
- 2024-09-20Introduction to Total.js UI Builder: A Beginner’s Guide
- 2024-09-13Total.js v5: #06 Understanding File Routing