Performance

What is it?

The act of performing; carrying into execution or action; execution; achievement; accomplishment; representation by action; as, the performance of an undertaking of a duty.
http://en.wiktionary.org/wiki/performance
Doing something that has a result.
Jason Parrott (Me)

Performance

  • Too general
  • Let's focus on this definition...

Performance

Final definition

        var doingSomething = 'Displaying a web page';
        var result = 'speed';

        var performance = doingSomething + ' with _adjective_' + result;

        function performanceDefinition(adjective) {
          console.log(
            performance.replace(/_adjective_/g, adjective ? adjective + ' ' : '')
          );
        }

        performanceDefinition();
        // > "Displaying a web page with speed"
      

Performance

What we will focus on

        var i, il;
        var types = [
          'awesome', 'good', 'bad', 'terrible'
        ];

        for (i = 0, il = types.length; i < il; i++) {
          performanceDefinition(types[i]);
        }

        // > "Displaying a web page with awesome speed"
        // > "Displaying a web page with good speed"
        // > "Displaying a web page with bad speed"
        // > "Displaying a web page with terrible speed"
      

Performance

Types of performance on the web

Types of Performance on the Web

    HTML

  • Network
  • Resource
  • Parsing
  • Layout
  • Painting
  • Compositing

    JavaScript

  • Raw execution
  • Usage of DOM
  • Canvas
  • A million others...

Layout

In other words, reflow

Layout

What is it?

  • Calculation of element's position and size
  • Many different layout models
  • Messy and hidden inside of the CSS2 specification
  • New layout models that are very clear and easy to understand.
    • Flexbox (http://www.w3.org/TR/css3-flexbox/)
    • Multi-column (http://www.w3.org/TR/css3-multicol/)
    • Grid (http://www.w3.org/TR/css3-grid-layout/)

Layout

Why do we care?

  • Most average web sites have huge numbers of nodes to layout
  • Yahoo.co.jp had 2153 nodes (text and elements) (And that's optimized!)

Layout

How Positioning Works

How Positioning Works

Types of Positioning

  • Normal Flow
    • position: static
    • position: relative
  • Floating (float: left/right)
  • Absolute
    • position: absolute
    • position: fixed

Normal Flow

Static

  • The simplest
  • Create boxes for containers (like div)
  • Flow the boxes vertically, one box per row
  • Flow content (line-boxes) horizontally inside boxes

Normal Flow

Relative

  • Move from normal position by x,y
  • All relative layouts first do a static layout

Floating

  • Positions elements on the left or right side of another float element or the current block container
  • Very difficult to plan and understand
  • Can be slow or fast

Absolute

Absolute absolute

  • Positions elements relative to the current containing block, in CSS units, to an exact location
  • Messy if not managed properly
  • Layout is fast

Absolute

Fixed absolute

  • A subclass of regular absolute
  • Always positions relative to the viewport (screen)
  • Layout is very fast

Layout

Positioning Tips

Order of Speed

  • Fixed > absolute > static > relative > float
  • Float can be faster or slower
  • As you go deep in the DOM tree, static, relative and float get slower

Relative Positioning Evil

  • Don't use position:relative if you don't need to
        div { position: relative; }
        .moveable_class { position: absolute; !important }
      
        <div>Hello</div>
        <div>world!</div>
        <div>How are you today?</div>
        <div>
          <div class="moveable_class" style="left: 34px; top: 50px">Dandy</div>
        </div>
        <div>:)</div>
      

Layout

With JavaScript

JavaScript is Scary

  • JavaScript allows you to do cool stuff
  • It also allows you to do something evil
        function HTMLHtmlElement() {
          Object.defineProperty(this, 'offsetWidth', {
            get: function() {
              // Calculate all child elements' positions and sizes!
            },
            configurable: false,
            enumerable: true
          });
        }

        var element = new HTMLHtmlElement();
        for (var i = 0; i < 10000; i++) { console.log(element.offsetWidth) }
      

Offset and Client Properties

Question

  • offsetTop
  • offsetLeft
  • offsetWidth
  • offsetHeight
  • clientTop
  • clientLeft
  • clientWidth
  • clientHeight

Which of the above properties cause a lot of calculations do happen in the background?

http://www.w3.org/TR/cssom-view/

Offset and Client Properties

Answer

All of them

Offset and Client Properties

These properties all calculate their own size (padding edge or border edge).

All of their children's sizes are also be calculated.

Offset and Client Properties

  • If you know the value won't change, cache it and use it
  • If you access them in the middle of changing other properties, it is possible to force a reflow

Inserting Elements Via the DOM

  • A common thing to do since the DHTML days
        var element, body = document.body;
        for (var i = 0; i < 500; i++) {
          element = document.createElement('div');
          body.appendChild(element);
          element.style.width = element.style.height = '40px';
        }
      
  • There are a couple things you should not do here

Inserting Elements Via the DOM

        var element, body = document.body;
        var fragment = document.createDocumentFragment();
        for (var i = 0; i < 500; i++) {
          element = document.createElement('div');
          element.style.width = element.style.height = '40px';
          fragment.appendChild(element);
        }
        body.appendChild(fragment);
      

DocumentFragment

Some interesting facts

  • They used to be way faster than anything else
  • With recent optimizations in browsers, they are roughly the same speed as the normal appendChild
  • Elements inside a DocumentFragment have no layout box
    • Almost all values in CSS are uninitialized or 0
      • Try it out with window.getComputedStyle!
    • Impossible to make a reflow or paint happen

The Remove/Re-add Rule

There are many articles on the Internet saying that it is faster to remove the group of nodes you are about to edit from the DOM tree (removeChild), edit all the nodes (avoiding reflow), and re-insert them back in to the same place in the DOM tree.

  • This used to be true and still is in some cases
  • It is now false in all situations that I have personally tested that use GPU mode for rendering
    • Like transform: translate3d(x,y,z)
    • Now-a-days, the browser will get slower due to a paint that occurs from re-adding the nodes

Layout

Results

Layout

Results

  • Fixed > absolute > static > relative > float
  • Remember JavaScript properties can be slow just by accessing them
  • Cache computed values if possible
  • Edit element properties before adding them
  • Use DocumentFragment
  • Do not use the Remove/Re-add Rule in GPU mode

Painting

How the browser draws

Painting

What is is?

  • After layout, browsers need to draw elements to the screen
  • Chrome/WebKit calls this painting
  • Calculates what elements are visible now and draw them

Painting

When it happens

  • Viewing (loading) the page the first time
  • Scrolling the page
  • Hiding an element and re-showing it again in GPU mode
  • Changing visual properties of an element
  • Possibily when a decendant (or possibly ancestor) element changes

Painting

Seeing when it happens

  • In Chrome, open up the developer tools
  • Switch to the Timeline panel
  • Hit the record button at the bottom
  • Play with your web site
  • Return to the developer tools and hit the record button again to stop recording
  • Look at the data!

Painting

Some fun

Let's see what happens when we try out the Remove/Re-add Rule!

Painting

Results

Painting

Results

  • Painting is difficult to optimize
  • Check the developer tools timeline feature
  • Avoid shadow related CSS

Compositing

Mixing everything together

Compositing

What is it?

  • Taking painted elements and mixing them in the correct order on the screen
  • Mostly a GPU thing
  • Looks at information like z-index, transform's Z properties, opacity and layout layers

Compositing

When it happens

  • After a paint
  • After position-related properties change on an element

Compositing

GPU mode

GPU mode

What is it?

  • A method to render everything to the screen
  • Usage of 3D APIs (OpenGL, DirectX, etc) for everything
  • In GPU mode, browsers translate a web page in to a 3D scene!

GPU mode

When is it used?

  • Using a 3D related CSS property
  • Using HTML Canvas in a modern browser
  • Depending on platform and browser flags, always
  • In the future, probably always!

GPU mode

So?

  • Every element is at least a single rectangle with a texture applied to it (CSS style)
  • It should always be used if possible
  • Unless you hit some of GPU mode's weaknesses...

GPU mode

Annoying fun!

The Remove/Re-add Rule and GPU mode with transform: translate3d instead of left and top!

GPU mode

Annoying fun fixed!

Without the Remove/Re-add Rule with translate3d!

Compositing

Results

Compositing

Results

  • Use GPU mode if possible
  • Imagine all objects are textures in memory
  • Test for devices that have bugs in GPU mode
  • Do not use the Remove/Re-add Rule in GPU mode
  • Remember that textures are destroyed when their element is removed from the DOM

HTML Canvas

2D is actually 3D

HTML Canvas

What is it?

  • An element for drawing
  • Provides 2D and 3D API's (Canvas and WebGL)
  • Useful for games and interesting web sites

HTML Canvas

How it works

  • A simple implementation would directly draw pixels as you do commands
  • Drawing pixels is slow
  • Instead amazing technologies exist to speed things up

Accelerated Canvas

  • GPU mode
  • Canvases exist as a texture in the GPU
  • Canvas commands get translated in to some 3D command to be run on the GPU

Accelerated Canvas

  • Imagine fillRect(x, y, w, h) being a rect polygon filled with the current fillStyle colour and/or pattern texture
  • Transforming paths and images is very fast
  • Drawing paths is not awesomely fast
  • drawImage is awesomely fast

Deferred Canvas

  • Chrome optimization for Canvas called deferred 2d Canvas
  • Takes GPU commands from accelerated Canvas and waits to execute them
  • Executes them when that canvas is used
  • Many optimizations like merging drawing commands together possible
  • Transparent to the developer!

drawImage

  • No reason not to use drawImage
  • Literally copying pixels directly in the GPU. Can't get any faster

Use fillStyle and bezierCurveTo each frame to draw all 500 hearts

Cache all 500 hearts as individual Canvases and drawImage them

HTML Canvas

Results

HTML Canvas

Results

  • Modern Canvas is actually 3D
  • Uses GPU mode
  • Transforming paths and images is very fast
  • Drawing paths is not as fast as drawImage
  • Always use drawImage
  • Browsers are getting smarter and faster every day

requestAnimationFrame

  • What about the infamous requestAnimationFrame?
  • You should use it in real world projects!
  • Allows you to render only when the browser will actually render to the screen
  • setTimeout will render faster than what is actually displayed
  • Optimized so that render/drawing related operations run faster than in normal execution

Summary

Summary

Things we covered

  • Overview of how to make many parts of the browser faster
  • How to make layout a bit faster, especially in JavaScript
  • Overview of what painting is and how to debug it for speed
  • Overview of what compositing and GPU mode is and how to work with it
  • How to use HTML Canvas (2D) a faster

Thank You!

Contact Information