Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Micro-optimization Trap

DZone's Guide to

The Micro-optimization Trap

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Yesterday, a couple of my friends and I were discussing a CoffeeScript topic. In short, given the following code in CoffeeScript:

class Cat
  type: -> 'cat'
  meow: -> 'meow meow mee..ow'

The compiler produces this in JavaScript:

var Cat;

Cat = (function() {

  function Cat() {}

  Cat.prototype.type = function() {
    return 'cat';
  };

  Cat.prototype.meow = function() {
    return 'meow meow mee..ow';
  };

  return Cat;

})();

As you can see here, the prototype method definitions use the prefix Cat.prototype repeatedly, which could be compressed using Closure as follows:

var Cat;

Cat = (function() {

  function Cat() {}

  var p = Cat.prototype;

  p.type = function() {
    return 'cat';
  };

  p.meow = function() {
    return 'meow meow mee..ow';
  };

  return Cat;

})();

This Closure form is for sure less bloated than the one produced by CoffeeScript. And on IE7, each Cat.prototype lookup takes about a microsecond, so, the closure form quite literally yields a microsecond optimization! When one zooms into such micro-optimizations, other, bigger fish are easily missed.

For example, even though the output is a little bloated from the CoffeeScript compiler, the CS source code is ridiculously simpler and shorter, even for this tiny example. But that’s not the only reason why one would use CS. If for nothing else, CS produces JavaScript Lint for free. I’m not saying one has to use CoffeeScript, but this serves as an example scenario. When making a decision, a tunnel-vision into the micro-optimization may as well be a trap.



Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Published at DZone with permission of S M Sohan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}