Wednesday, April 25, 2007

Garbage Collection? That's gross!

"Garbage Collection" probably sounds like a strange term if you've never heard of it before. So what is it? Well, you've all probably heard of a "memory leak" before. Garbage Collection, or GC, is essentially an attempt to prevent memory leaks. Back in the old days, developers had to be very diligent about cleaning up after themselves. If an object was allocated repeatedly but never "destroyed" or cleaned up the system would gradually use more and more memory until there was no more available memory and the application would crash.

Today, platforms like Java, .Net, Javascript, Perl, Ruby, and PHP have GC built-in. In platforms with GC, objects that are no longer referenced (because the reference has gone out of scope or because the variable was set to null) become eligible to be automatically destroyed and the memory used made available for new allocations. Notice that i said they become eligible; the objects are not immediately cleaned up when they go out of scope. The garbage collector only performs the collection when it is necessary, such as when the system is running low on memory.

Javascript has the ability to be garbage collected or to use explicit memory management when necessary or desired with the delete keyword. The two graphs below show the difference.

The first graph shows memory consumption over time while the garbage collector is allowed to manage the memory.

The second graph shows the same thing while the program manages it's own memory by explicitly deleting the objects when it is done with them.

   1: <%@ Page Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs" Inherits="ItsJustJavascript._Default" %>
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
   4: <html xmlns="">
   5: <head id="Head1" runat="server">
   6:     <title>Untitled Page</title>
   7: </head>
   8: <body>
   9:     <form id="form1" runat="server">
  10:         <div>
  11:             <button onclick="cancel = false; useMemory(false);">
  12:                 start (normal)</button>
  13:             <button onclick="cancel = false; useMemory(true);">
  14:                 start (self cleanup)</button>
  15:             <button onclick="cancel = true;">
  16:                 stop</button>
  17:             <br />
  18:             <input type="text" id="output" />
  19:         </div>
  20:     </form>
  21:     <script type="text/javascript">
   2:     var cancel = false;
   3:     var output = document.getElementById("output");    
   5:     function useMemory(selfCleanUp)
   6:     {
   7:         if (cancel) return;
   9:         output.value = (new Date()).toString();
  10:         for (var i = 0; i<100000; i++)
  11:         {
  12:             var foo = new Object(); //just consume a small amount of memory
  13:    = new Object(); // and a bit more memory, plus an expando!
  14:             if (selfCleanUp)
  15:             {
  16:        = null;
  17:                 delete;
  18:                 foo = null;
  19:                 delete foo;
  20:             }
  21:         }
  23:         window.setTimeout("useMemory(" + selfCleanUp + ")", 1);
  24:     }
  22: </body>
  23: </html>

Additional Info:

Monday, April 23, 2007

Presto Expando

It's hard to know where to start, but you've got to start somewhere, right?

JavaScript is a very dynamic language. That basically means that objects can be created and modified at runtime. It is also very loosely-typed which means that you can treat a string variable as an integer or an integer as a date, or a date as a string, or... well, you get the point.

So what do I mean by "objects can be created and modified at runtime"? In static languages, the members (attributes, properties, methods, etc.) and behaviors of a type are explicitly defined at design-time and then compiled. After compilation you cannot add or remove any of the members. I suppose you've already guessed what i'm going to say next. In dynamic languages (depending on the degree of dynamicism), any member can be added, removed, or replaced at runtime. In Javascript, members you add at runtime are commonly called "expando properties".

   1: var someObject = new Object();
   3: //calls builtin toString method
   4: alert(someObject.toString());
   6: // adding an attribute
   7: someObject.myExpando = "hello expando";
   9: // replaces builtin toString method
  10: someObject.toString = function()
  11: {
  12:     return this.myExpando;
  13: }
  15: // notice how the toString method has been replaced
  16: alert(someObject.toString());
  18: // adding a new method to the new object
  19: someObject.tellTime = function()
  20: {
  21:     alert(new Date());
  22: }
  24: someObject.tellTime();
  26: //removing the method we just added
  27: delete someObject.tellTime;
  29: //calling the method now will be an error
  30: try
  31: {
  32:     someObject.tellTime();
  33: }
  34: catch(e)
  35: {
  36:     alert(e.message);
  37: }

Additional Info:

Friday, April 20, 2007

It's just Javascript, right?

Recently I realized that most developers I've known (and therefore, probably most developers in the world) think of Javascript as just:

  • a bunch of variables,
  • inline code in an onClick attribute, and
  • global methods on a webpage.

How many of you are saying "yeah, what else is there?"; raise your hands...

I'll discuss the language in more detail in a series that will start out simple and then build upon itself. Hopefully each episode will leave you dying to find out what happens next - like an episode of Lost or 24. Some of the episodes will be called:

  1. Presto Expando
  2. Garbage Collection? That's gross!
  3. Boolean. Not the meat cubes; and not the gold bricks.
  4. Object Oriented? You can't even define classes, can you?
  5. Prototype? But hasn't Javascript been around for a while now?
  6. Functional? Of course it is, I mean, I've seen it work.
  7. What's in the Dictionary?
  8. Who is this J[a]SON i've been hearing about?
  9. The library formerly known as "Atlas"