... = str.split("'").join("\'");
<avm@pendragon.be>Choose API methods carefully. There are often several ways of doing something, but only one is most efficient.
For example, avoid:
... = str.split("'").join("\'");
prefer:
... = str.replace(/'/g, "\'");
function Point(x, y) { this.x = x; this.y = y; } var p1 = new Point(11, 22); var p2 = new Point(33, 44); // At this point, p1 and p2 have a shared hidden class p2.z = 55; // warning! p1 and p2 now have different hidden classes!
Avoid calling expensive objects in a loop.
Example: create a regular expression once, before entering the loop
Avoid:
function on(events, ...) { events = events.split(/\s+/); ... }
Prefer:
var eventSplitter = /\s+/; function on(events, ...) { events = events.split(eventSplitter); ... }
More generic API’s are usually slower.
For example, avoid:
arr.slice(n)[0] // with n < 0, returns the n-th to last element
prefer:
arr[arr.length + n] // with n < 0, does the same
(because slice(n) makes a partial copy of the array into another array)
And many others…
in Chrome:
>> Developer Tools >> ⋮ >> More tools >> JavaScript Profiler >> Start
…
>> Stop
Then, select "Chart" to get a flame chart.
Or, select "Heavy (Bottom Up)" to get histogram data.
in Chrome:
>> Developer Tools >> Performance >> ⚫ (Record)
…
>> Stop
Same data as CPU Profiler, but in an integrated timeline view
https://developers.google.com/web/tools/chrome-devtools/rendering-tools/
→ https://developers.google.com/web/tools/chrome-devtools/rendering-tools/js-execution
→ https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/timeline-tool#make-a-recording
Performance Issues and Optimizations in JavaScript: An Empirical Study. Marija Selakovic and Michael Prade. Technical Report. TU Darmstadt, Department of Computer Science. 2015-Oct. http://mp.binaervarianz.de/JS_perf_study_TR_Oct2015.pdf
Performance Tips for JavaScript in V8 https://www.html5rocks.com/en/tutorials/speed/v8/
Online tests:
<script> var dummy; function foo() { var sum = 0; for (var i = 0; i < 100000000; i++) { sum += Math.sqrt(i); } setTimeout(function () { dummy = sum; }, 1000); } foo(); // This method is too slow and puts too much load on the memory </script> Done.