SlideShare a Scribd company logo
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.

More Related Content

What's hot (19)

PDF
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
PDF
Swift Sequences & Collections
CocoaHeads France
 
PDF
Angular and The Case for RxJS
Sandi Barr
 
PDF
Map kit light
CocoaHeads France
 
PDF
Ns2: OTCL - PArt II
Ajit Nayak
 
PDF
Ns2: Introduction - Part I
Ajit Nayak
 
PDF
Go Memory
Cloudflare
 
PDF
NS2: AWK and GNUplot - PArt III
Ajit Nayak
 
PDF
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
PDF
Oop assignment 02
MamoonKhan39
 
PDF
RxJS101 - What you need to know to get started with RxJS tomorrow
Viliam Elischer
 
PPTX
MiamiJS - The Future of JavaScript
Caridy Patino
 
PDF
Openstack taskflow 簡介
kao kuo-tung
 
PDF
Debugging JavaScript with Chrome
Igor Zalutsky
 
PPTX
Introduction tomongodb
Lee Theobald
 
PDF
RxJS 5 in Depth
C4Media
 
PDF
Kapacitor Alert Topic handlers
InfluxData
 
PDF
RxJS Evolved
trxcllnt
 
PDF
Будь первым
FDConf
 
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
Swift Sequences & Collections
CocoaHeads France
 
Angular and The Case for RxJS
Sandi Barr
 
Map kit light
CocoaHeads France
 
Ns2: OTCL - PArt II
Ajit Nayak
 
Ns2: Introduction - Part I
Ajit Nayak
 
Go Memory
Cloudflare
 
NS2: AWK and GNUplot - PArt III
Ajit Nayak
 
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
Oop assignment 02
MamoonKhan39
 
RxJS101 - What you need to know to get started with RxJS tomorrow
Viliam Elischer
 
MiamiJS - The Future of JavaScript
Caridy Patino
 
Openstack taskflow 簡介
kao kuo-tung
 
Debugging JavaScript with Chrome
Igor Zalutsky
 
Introduction tomongodb
Lee Theobald
 
RxJS 5 in Depth
C4Media
 
Kapacitor Alert Topic handlers
InfluxData
 
RxJS Evolved
trxcllnt
 
Будь первым
FDConf
 

Similar to W3C HTML5 KIG-How to write low garbage real-time javascript (20)

PDF
Your java script library
jasfog
 
PDF
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
Doris Chen
 
PDF
From Zero to Hero – Web Performance
Sebastian Springer
 
PPTX
TiConnect: Memory Management in Titanium apps
Tim Poulsen
 
PPTX
Advanced JavaScript
Zsolt Mészárovics
 
PDF
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Doris Chen
 
PPTX
Awesomeness of JavaScript…almost
Quinton Sheppard
 
PPT
Talking trash
michael.labriola
 
PDF
Kevin Whinnery: Write Better JavaScript
Axway Appcelerator
 
PDF
There's garbage in our code
Adrian Oprea
 
PDF
Secrets of JavaScript Libraries
jeresig
 
PPTX
JavaScript (without DOM)
Piyush Katariya
 
PDF
ES6 - Next Generation Javascript
RameshNair6
 
PDF
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
PPT
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
PDF
JavaScript: Patterns, Part 1
Chris Farrell
 
ZIP
Javascript Everywhere
Pascal Rettig
 
KEY
JavaScript Growing Up
David Padbury
 
KEY
Your Library Sucks, and why you should use it.
Peter Higgins
 
PDF
JavaScript - new features in ECMAScript 6
Solution4Future
 
Your java script library
jasfog
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
Doris Chen
 
From Zero to Hero – Web Performance
Sebastian Springer
 
TiConnect: Memory Management in Titanium apps
Tim Poulsen
 
Advanced JavaScript
Zsolt Mészárovics
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Doris Chen
 
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Talking trash
michael.labriola
 
Kevin Whinnery: Write Better JavaScript
Axway Appcelerator
 
There's garbage in our code
Adrian Oprea
 
Secrets of JavaScript Libraries
jeresig
 
JavaScript (without DOM)
Piyush Katariya
 
ES6 - Next Generation Javascript
RameshNair6
 
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
JavaScript: Patterns, Part 1
Chris Farrell
 
Javascript Everywhere
Pascal Rettig
 
JavaScript Growing Up
David Padbury
 
Your Library Sucks, and why you should use it.
Peter Higgins
 
JavaScript - new features in ECMAScript 6
Solution4Future
 
Ad

More from Changhwan Yi (15)

PDF
Web sessions in Developer Conferences
Changhwan Yi
 
PDF
JavaScript Engine and WebAssembly
Changhwan Yi
 
PDF
2013 W3C HTML5 Day Conferences:HTML5 Game App 개발 및 이슈
Changhwan Yi
 
PDF
Html5 게임 기술의 개요
Changhwan Yi
 
PDF
동국대 앱창작터 5일차:Cocos2d-X 확장기능
Changhwan Yi
 
PDF
동국대 앱창작터 4일차:Cocos2d-X 고급기능
Changhwan Yi
 
PDF
동국대 앱창작터 2일차:Cocos2d-X 기본기능
Changhwan Yi
 
PDF
동국대 앱창작터 1일차:Cocos2d-X 소개, 환경설정, 주요개념
Changhwan Yi
 
PDF
W3C HTML5 KIG-The near future of the web platform
Changhwan Yi
 
PDF
W3C HTML5 KIG-The complete guide to building html5 games
Changhwan Yi
 
PDF
차세대 웹비즈니스를 위한 "HTML5"
Changhwan Yi
 
PDF
WoO 2012-Web 서비스 기술
Changhwan Yi
 
PDF
W3C HTML5 KIG-Typed Arrays
Changhwan Yi
 
PDF
하이브리드 앱(Hybrid App)
Changhwan Yi
 
PDF
W3C HTML5 KIG-HTML5 Game Performance Issue
Changhwan Yi
 
Web sessions in Developer Conferences
Changhwan Yi
 
JavaScript Engine and WebAssembly
Changhwan Yi
 
2013 W3C HTML5 Day Conferences:HTML5 Game App 개발 및 이슈
Changhwan Yi
 
Html5 게임 기술의 개요
Changhwan Yi
 
동국대 앱창작터 5일차:Cocos2d-X 확장기능
Changhwan Yi
 
동국대 앱창작터 4일차:Cocos2d-X 고급기능
Changhwan Yi
 
동국대 앱창작터 2일차:Cocos2d-X 기본기능
Changhwan Yi
 
동국대 앱창작터 1일차:Cocos2d-X 소개, 환경설정, 주요개념
Changhwan Yi
 
W3C HTML5 KIG-The near future of the web platform
Changhwan Yi
 
W3C HTML5 KIG-The complete guide to building html5 games
Changhwan Yi
 
차세대 웹비즈니스를 위한 "HTML5"
Changhwan Yi
 
WoO 2012-Web 서비스 기술
Changhwan Yi
 
W3C HTML5 KIG-Typed Arrays
Changhwan Yi
 
하이브리드 앱(Hybrid App)
Changhwan Yi
 
W3C HTML5 KIG-HTML5 Game Performance Issue
Changhwan Yi
 
Ad

Recently uploaded (20)

PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Python basic programing language for automation
DanialHabibi2
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 

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 동국대 멀티미디어공학과 이창환 ([email protected])
  • 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 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!
  • 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 [] to an array this creates a new empty array and garbages the old one! To write arr.length = 0
  • 8. 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);
  • 9. 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
  • 10. 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;
  • 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 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.
  • 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.

Editor's Notes