Sunday, January 16, 2011

JavaScript Performance: Creational Patterns

Which JavaScript creational pattern is the most efficient? Is it an object literal, functional, or pseudoclassical object? With JsTestDriver, I setup a quick performance test to gather the metrics.


Creational Patterns to Test

I tested the three most popular creational patterns in JavaScript. Object literals, functional objects, and pseudoclassical objects. In particular, I wanted to test their singleton and instance based execution times.
/*
* Pseudoclassical object designed as a singleton
*/

var PseudoclassicalSingleton = new function(){
this.getName = function(){
return 'Pseudoclassical';
};
};

/*
* Functional object designed as a singleton
*/

var FunctionalSingleton = (function(){
return {
getName: function(){
return 'Functional';
}
};
})();

/*
* Object literal (implicitly singleton)
*/

var ObjectLiteralSingleton = {
getName: function(){
return 'ObjectLiteral';
}
};

/*
* Pseudoclassical object designed as a non-singleton
*/

var PseudoclassicalInstance = function(){
this.getName = function(){
return 'Pseudoclassical';
};
};

/*
* Functional object designed as a non-singleton
*/

var FunctionalInstance = function(){
return {
getName: function(){
return 'Functional';
}
};
};


Performance Test Runner

I setup JsTestDriver to execute the test cases against Firefox. One advantage of JsTestDriver is I can run my test cases against any browser! Each performance test will instantiate its creational pattern 1.4 million times as indicated by the RUN_TIMES constant. Additionally, I ran the performance test suite twenty times to gather an adequate average.
CreationalPatternsPerformanceTest = TestCase("CreationalPatternsPerformanceTest");

var RUN_TIMES = 1400000;

var performanceTest = function(name, f){
console.time(name);
for (var i = 0; i < RUN_TIMES; i++){
f();
}
console.timeEnd(name);
};

CreationalPatternsPerformanceTest.prototype.testResponseTimes = function(){
performanceTest("ObjectLiteral (singleton)", function(){
ObjectLiteralSingleton.getName();
});
performanceTest("Pseudoclassical (singleton)", function(){
PseudoclassicalSingleton.getName();
});
performanceTest("Functional (singleton)", function(){
FunctionalSingleton.getName();
});
performanceTest("Pseudoclassical (instance)", function(){
new PseudoclassicalInstance().getName();
});
performanceTest("Functional (instance)", function(){
FunctionalInstance().getName();
});
};



Performance Test Results
 Object Literal (singleton)Pseudoclassical (singleton)Functional (singleton)Pseudoclassical (instance)Functional (instance)
Avg (ms)10931095109433013341
Min (ms)10701064106232253246
Max (ms)11121114111334603476



Areas of Interest


I had three specific comparisons I wanted to evaluate heading into this experiment:
  1. Object literals vs the others (functional and pseudoclassical): I knew object literals were going to be the most efficient. However, I really wanted to see how much faster they really are. The result was surprising. Object literals (1093 ms) barely out performed functional (1094 ms) and pseudoclassical (1095 ms) response times. This difference is really negligible. Unlike object literals, functional and pseudoclassical objects can provide security. And the performance degradation is almost non-existent.
  2. Functional vs Pseudoclassical: There are always debates over these two objects. While I personally prefer pseudoclassical objects when security is a concern I definitely wanted to see which one was the more performant option. In the end, neither pattern distanced itself from the other in regards to performance.
  3. Singletons vs Instance based Objects: I knew singletons would be the most efficient. However, I wanted to see what this difference really was. On average, singletons were three times faster.


Lessons Learned

  1. Prefer singletons over instance based objects when possible.
  2. Prefer object literals when you are not concerned about privacy.
  3. The performance metrics alone are not enough to sway the functional vs pseudoclassical debate.

Sunday, January 2, 2011

JavaScript: Securing Pseudoclassical Objects

Which JavaScript pattern do you prefer for object creation? Functional or pseudoclassical? This question makes for a very interesting debate. The first time I read JavaScript: The Good Parts I was sold on the functional pattern based upon the knowledge that it was the only pattern that supported privacy. However, the pseudoclassical pattern can be secured! Based upon the fact that pseudoclassical objects can be secured and its many additional advantages make it the ideal choice for object creation.


Securing Pseudoclassical Objects

/**
* Pseudoclassical object with private variables and functions.
*
* @constructor
* @param {string} name
* @param {number} age
*/

var Person = function(name, age) {

/** @public variable */
this.name = name || 'Brad';

/** @private variable */
var age = age || 34;


/** @private function */
function setAge(a) {
age = a;
}

/** @public function with access to private methods and variables (privileged) */
this.getAge = function () {
return age;
};
};


Why is Everything Public?

Security is not often documented within JavaScript books and I rarely see examples where developers secure their JavaScript objects. Typically, everything is exposed publicly. If you develop mobile applications with Titanium or are developing a JavaScript framework you absolutely must apply security with either the functional or pseudoclassical pattern. And of all the Titanium code I have read over the past month not a single example or sample application was concerned about privacy. Training can remedy this problem.


JavaScript Code Completion

auto completeA simple way to quickly view the publicly available methods of an object is with code completion. For example, the Aptana Eclipse plug-in has code completion built-in and works very well for JavaScript development.

Monday, November 29, 2010

Becoming a MacBook Pro Ninja

mac book proI have always been the PC guy in those funny Mac
commercials. I knew very little about Macs a month ago. In fact, I had to consult the owners manual to find the seamlessly integrated power button on the shiny new Mac Book Pro! I didn't feel too bad, I challenged another PC guy to find it and they failed too:) Being a novice at anything can be extremely frustrating. As a novice I set a simple goal. Learn everything about this all-aluminum, uni body machine. After reading MacBook Pro Portable Genius, a few magazines, and many online tips I finally feel very comfortable in the drivers seat. Here is a very brief recap of what I discovered on my journey.

Favorite Features

  1. Trackpad gestures:
    The trackpad is unquestionably the most powerful feature you will find on any laptop and it is exclusive to MacBooks. Who needs a mouse? I am more efficient with the trackpad! Enable "tap to click" for even greater efficiency gains.
  2. Expose:
    Expose is also totally unique to Macs and offers a convenient layout for switching between open windows. Additionally, Application Switcher and Spaces (also unique) each offer efficient capabilities for navigating your workspace. These features will definitely make you more efficient while multitasking.
  3. Security:
    The security settings are powerful and simple to setup. The settings include: account management, password enforcement, data encryption, firewall protection, secure notes, SSO capabilities, and parental controls. Each can be configured within Settings or Key Chain.

Top Four Things To Customize When Setting Up

  1. Enable Firewall:
    If you access public WIFI, setting up your firewall is a must. WIFI is the most vulnerable network you can access. Configure your settings to be most restrictive (block all incoming connections) and adjust as necessary if you need to allow network or web sharing.
  2. Require Passwords:
    Most users disable passwords on personal devices for convenience. I will always opt for security.
  3. Enable File Vault Encryption:
    This encrypts the entire home directory. I searched for benchmark studies and they only revealed minor performance degradation. If my laptop ends up in the wrong hands at least the malicious user won't be able to login or physically read my hard drive.
  4. Adjust Energy Savings:
    Dim the backlit keyboard, reduce screen brightness, and adjust the energy saver settings to preserve battery life.

Most Frustrating Features

  • Speech recognition:
    This is an interesting feature that is hit or miss. A few commands work well ("open my browser") while others rarely work ("tell me a joke"). In the end, the trackpad reigns supreme.
  • No trackpad gesture for Spaces:
    Looks like the only alternative is to use a hot corner or keyboard shortcut.

Features With Potential That I May Never Use

  • Dashboard:
    I have setup several active widgets for weather and iTunes but I can access these features outside of dashboard too. The availability of useful widgets will drive my usage of this feature.
  • Text-to-speech:
    This is a nice feature but I only see myself using it while reading an online book.
  • MobileMe:
    I can not justify the yearly cost for Apple's cloud storage when a simple flash drive does the job at a lower cost.

Mac Book Resources

Tuesday, September 14, 2010

Cleaner Code with One Simple Technique


Clean code bookWhat is the simplest technique you can apply to write cleaner code? Clean Code by Robert C. Martin is a very good book that focuses exclusively on writing cleaner code. I read this book several months ago and at a recent code review I was again reminded of the value of this simple technique. The simplest technique to apply for writing cleaner code is to keep functions small!



Advantages of Small Functions

  • Functions perform one specific responsibility (single responsibility principle)
  • Functions become very readable
  • Functions are more likely to descend only one level of abstraction (tip G34 from Bob's book)
  • Small functions promote reusability and help eliminate duplication
  • Your favorite IDE makes extract method so simple
  • Small functions adhere to these valuable coding principles by design


Ideal Function Size

"Continue to extract methods until you can not extract methods anymore. Extract until you drop!" This is Bob's recommendation from his online presentation of Bad Code and Craftsmanship. Personally, I couldn't agree more. For the past three months I have been following this practice and this simple technique has a high return on investment.



Additional Clean Code Tips

Looking for additional clean code tips? Chapter 17 (Smells and Heuristics) in Bob's book is a very quick read and covers sixty-six valuable coding practices. Alternatively, Bob discusses many clean code practices in his online presentation. In fact, he leads off the discussion by focusing on the importance of small functions!