Javascript Garbage Collection pauses
I am trying to create a simple game engine in JavaScript with WebGl,开发者_运维问答 but I am having some undesired problems with JavaScript in general, which I hope can be avoided. Besides the overall lack of performance with JavaScript, I am having some strange pauses when rendering with WebGl, which happen periodically, once every second or so. I assume this has to happen with GC in JavaScript. Is there anyway to minimize these "stutters"? Are there any common practices I should know, a way to force, at least part of the garbage collection, to happen at a time that I can control?
I know these are simple questions, but I am fairly new to JavaScript, and searching on the internet did not give me to many useful information.
Re-use objects as often as possible. If you are creating dozens of objects (like vectors and matrices) for each rendered frame then you will definitely receive GC-related stuttering. So when you are using a scene-graph based approach for rendering your game you might want to cache objects in the scene graph nodes for example. Or you can use the Object Pool Pattern. In other languages like Java this technique is deprecated because the object creation and GC is so fast today that a object pool doesn't help anymore. But in JavaScript it might still help.
I had GC-stutter-problems in a JavaScript game I wrote last year and I solved it by rewriting my 2D vector engine so absolutely no new objects are created during frame rendering. Objects are only created once when the scene is build-up or new scene nodes are added to it. But displaying and animating the scene creates absolutely no new objects.
You may want to take a look at my 2D engine:
http://www.ailis.de/~k/hg/javascript/twodee/file/tip/src/main/javascript/twodee
You'll notice that I cache temporarily needed vectors and matrices in static fields and that I used mutable vector and matrix classes instead of immutable so existing vectors/matrices are modified instead of creating new result vectors/matrices when doing math with them.
精彩评论