Content

Typical causes of performance issues

Cause: Implementations

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, "\'");

Cause: Hidden classes

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!

Cause: Repetitions

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);
  ...
}

Cause: Generic API

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)

Causes…

And many others…

Profiling

CPU Profiler

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.

CPU Profiler

images/flamechart.png

CPU Profiler

images/heavy.png

Timeline recording

in Chrome:
>> Developer Tools >> Performance >> ⚫ (Record)

>> Stop

Same data as CPU Profiler, but in an integrated timeline view

Timeline recording

images/JS_Profile.png

Other topics

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:

Lower level languages

Exercise: Context promotion

contextPromotion.html
<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.

That’s all folks!