In this blog post we look into the micro optimizations of JavaScript code. These optimizations can improve performance in some specific cases.
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.
I often use bellow if statement:
if (value !== undefined && value !== null)
it can be replaced with simpler version:
if (value != null)
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:
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.