We’ve all seen it, perhaps even in our own code. It’s something I think we do because we’re not really sure what would happen if we didn’t do it. Here are some little tidbits of pointless code I’ve been seeing recently:
For starters, here’s a quick review of the default values of class fields:
class Classy { public var i:int; // 0 public var u:uint; // 0 public var n:Number; // NaN public var s:String; // null public var o:Object; // null public var a:Array; // null public var b:Boolean; // false public var r:RegExp; // null public var v:Vector.<int>; // null }
Make sure you know the above. When you do, you realize how pointless and bloated this is:
class Classy { public var i:int = 0 public var u:uint = 0 public var n:Number = NaN public var s:String = null public var o:Object = null public var a:Array = null public var b:Boolean = false public var r:RegExp = null public var v:Vector.<int> = null }
All of these assignment statements will result in bytecode that gets executed to change each variable to its current value. This wastes CPU cycles and increases the size of your SWF. It should be noted though that constants do require initialization.
The second and last case I’ll talk about today is the case of conditionals. Any expression you put in an if or the like will essentially be passed to the global Boolean function. Consider these if statements:
// Best at everything except being explicit if (obj) { } // Explicit, more typing, slow if (obj != null) { } // Sort of explicit, even more typing, slowest if (Boolean(obj)) { }
Keep this in mind as you write your conditionals. As a programmer you’re likely to type a lot. Make sure your typing really counts!
#1 by jwo on July 4th, 2010 · | Quote
Love the blog. I recently had to defend my usage of if (obj) over if (obj != null), glad to see I was vindicated.
Do you know if in simple situations are there any performance implications for using if..else statements of ternary operations?
e.g.
vs.
I have been trying to convince myself to run a test but been too lazy haha.
#2 by jackson on July 11th, 2010 · | Quote
I haven’t tested this directly, but I’ll take a look at it and let you know (perhaps via an article) if I find anything. One would hope that MXMLC generates the same bytecode, but some recent examples seem to, unfortunately, show otherwise.