HTML5 KIG 16차 모임

 How to write low
garbage real-time
        2012.5.15
  동국대 멀티미디어공학과
  이창환 (yich@dongguk.edu)
Things Related Article
http://www.scirra.com/
blog/76/how-to-write-
low-garbage-real-
time-javascript

Scirra

  http://
  www.scirra.com

  Construct 2: HTML5
  Game Engine
What’s GC Pause?

Javascript
  No explicit memory management
  Clean up -> execution pause.
One of the biggest obstacles to a smooth
experience
  60 fps (16ms), 100 msec or more
Simple techniques
Allocation

   the new keyword - e.g. new Foo().
   three syntax shortcuts for common uses of new:
      {} (creates a new object)
      [] (creates a new array)
      function () { ... } (creates a new function,
      which are also garbage-collected!)

Try to create the object on startup, and re-use the
same object
Avoid {}

objects with properties like { "foo": "bar" }

  commonly used in functions to return
  multiple values at once.

  The return value to the same (global)
  object every time and return that

  ! : bugs if you keep referencing the returned
  object which will change on every call!
re-cycle an existing
       object
Re-cycle an existing object (providing it has no prototype
chain) by deleting all of its properties, restoring it to an
empty object like {}

Use the cr.wipe(obj) function, defined as:

   ! : slow than using {}
// remove all own properties on obj,
effectively reverting it to a new object
cr.wipe = function (obj)
{
   for (var p in obj)
   {
      if (obj.hasOwnProperty(p))
         delete obj[p];
   }
};
Assigning [] to an array
 this creates a new empty array and
 garbages the old one!

 To write arr.length = 0
Functions
Functions are commonly created at startup
and don't tend to be allocated at run-time so
much

Ex) setTimeout() or requestAnimationFrame()
setTimeout((function (self) { return function () {
self.tick(); }; })(this), 16);

// at startup
this.tickFunc = (function (self) { return function () {
self.tick(); }; })(this);

// in the tick() function
setTimeout(this.tickFunc, 16);
Advanced techniques

Many of the convenient library functions in
Javascript create new objects.

Ex)

  the array slice() method returns a new
  array

  string's substr() returns a new string
Code Example

To delete the element at an index from an
array.
var sliced = arr.slice(index + 1);
arr.length = index;
arr.push.apply(arr, sliced);




for (var i = index, len = arr.length - 1; i < len; i++)
  arr[i] = arr[i + 1];

arr.length = len;
Recursive Functions
Use {} syntax to pass data along in recursive
functions

Better done with a single array representing a
stack which you push and pop for each level of
recursion.

Don't actually pop the array - you'll garbage
the last object in the array.

  Use a 'top index' variable
Avoid vector objects (1/2)

 Be convenient to have functions return these
 objects

 e.g.

    instead of getPosition() returning a
    vector2 object (vector2 with x and y
    properties)

    getX() and getY().
Avoid vector objects (2/2)

 e.g.

    Box2dWeb : 2D physics

    Spawns hundreds of b2Vec2 objects every
    frame constantly spraying the browser with
    garbage

    Create a recycling cache

        Box2Dweb-closure (https:/ /github.com/
        illandril/box2dweb-closure)
Conclusion
Difficult avoiding garbage entirely in
Javascript.

  Be a lot of work to eliminate garbage from
  Javascript code

  Bs possible to craft real-time Javascript
  with little to no garbage collector overhead

  Be essential for games and apps which
  need to be highly responsive.
Update
The use of 'delete'.

   Cause other slowdowns

   Construct2 use it very very sparingly in our engine.

Tradeoffs

   To use judgement to balance GC with other
   concerns.

A list of techniques we've found useful in our engine
and was not meant to be a complete reference.

W3C HTML5 KIG-How to write low garbage real-time javascript

  • 1.
    HTML5 KIG 16차모임 How to write low garbage real-time 2012.5.15 동국대 멀티미디어공학과 이창환 (yich@dongguk.edu)
  • 2.
  • 3.
    What’s GC Pause? Javascript No explicit memory management Clean up -> execution pause. One of the biggest obstacles to a smooth experience 60 fps (16ms), 100 msec or more
  • 4.
    Simple techniques Allocation the new keyword - e.g. new Foo(). three syntax shortcuts for common uses of new: {} (creates a new object) [] (creates a new array) function () { ... } (creates a new function, which are also garbage-collected!) Try to create the object on startup, and re-use the same object
  • 5.
    Avoid {} objects withproperties like { "foo": "bar" } commonly used in functions to return multiple values at once. The return value to the same (global) object every time and return that ! : bugs if you keep referencing the returned object which will change on every call!
  • 6.
    re-cycle an existing object Re-cycle an existing object (providing it has no prototype chain) by deleting all of its properties, restoring it to an empty object like {} Use the cr.wipe(obj) function, defined as: ! : slow than using {} // remove all own properties on obj, effectively reverting it to a new object cr.wipe = function (obj) { for (var p in obj) { if (obj.hasOwnProperty(p)) delete obj[p]; } };
  • 7.
    Assigning [] toan array this creates a new empty array and garbages the old one! To write arr.length = 0
  • 8.
    Functions Functions are commonlycreated at startup and don't tend to be allocated at run-time so much Ex) setTimeout() or requestAnimationFrame() setTimeout((function (self) { return function () { self.tick(); }; })(this), 16); // at startup this.tickFunc = (function (self) { return function () { self.tick(); }; })(this); // in the tick() function setTimeout(this.tickFunc, 16);
  • 9.
    Advanced techniques Many ofthe convenient library functions in Javascript create new objects. Ex) the array slice() method returns a new array string's substr() returns a new string
  • 10.
    Code Example To deletethe element at an index from an array. var sliced = arr.slice(index + 1); arr.length = index; arr.push.apply(arr, sliced); for (var i = index, len = arr.length - 1; i < len; i++) arr[i] = arr[i + 1]; arr.length = len;
  • 11.
    Recursive Functions Use {}syntax to pass data along in recursive functions Better done with a single array representing a stack which you push and pop for each level of recursion. Don't actually pop the array - you'll garbage the last object in the array. Use a 'top index' variable
  • 12.
    Avoid vector objects(1/2) Be convenient to have functions return these objects e.g. instead of getPosition() returning a vector2 object (vector2 with x and y properties) getX() and getY().
  • 13.
    Avoid vector objects(2/2) e.g. Box2dWeb : 2D physics Spawns hundreds of b2Vec2 objects every frame constantly spraying the browser with garbage Create a recycling cache Box2Dweb-closure (https:/ /github.com/ illandril/box2dweb-closure)
  • 14.
    Conclusion Difficult avoiding garbageentirely in Javascript. Be a lot of work to eliminate garbage from Javascript code Bs possible to craft real-time Javascript with little to no garbage collector overhead Be essential for games and apps which need to be highly responsive.
  • 15.
    Update The use of'delete'. Cause other slowdowns Construct2 use it very very sparingly in our engine. Tradeoffs To use judgement to balance GC with other concerns. A list of techniques we've found useful in our engine and was not meant to be a complete reference.