Click here to Skip to main content
15,886,689 members
Articles / Programming Languages / Javascript
Article

JavaScript like a boss: Understanding Fluent APIs

Rate me:
Please Sign up or sign in to vote.
4.88/5 (9 votes)
12 Jun 2015CPOL3 min read 15.1K   10   2
In this tutorial, I’ll walk through Fluent APIs – what to consider, how to write it, and cross-browser performance implications.

This article is a sponsored article. Articles such as these are intended to provide you with information on products and services that we consider useful and of value to developers

While designing babylon.js v2.0 (a library for building 3D on the web), I recently found myself wishing that more APIs were fluent – that is, I wish the community could more easily read, understand, and build upon the work while spending less time in the tech docs. In this tutorial, I’ll walk through Fluent APIs – what to consider, how to write it, and cross-browser performance implications.

Image 1

A fluent API, as stated by this Wikipedia article, is an implementation of an object oriented API that aims to provide for more readable code. jQuery for instance is a great example of what a fluent API allows you to do:

$('<div></div>')
    .html("Fluent API are cool!")
    .addClass("header")
    .appendTo("body");

Fluent API lets you chain function calls by returning this object.

We can easily create a fluent API like this:

var MyClass = function(a) {
    this.a = a;
}

MyClass.prototype.foo = function(b) {
    // Do some complex work   
    this.a += Math.cos(b);
    return this;
}

As you can see, the trick is just about returning the this object (reference to current instance in this case) to allow the chain to continue.

If you are not aware of how "this" keyword is working in JavaScript, I recommend reading this great article by Mike West.

We can then chain calls:

var obj = new MyClass(5);
obj.foo(1).foo(2).foo(3);

Before trying to do the same with babylon.js, I wanted to be sure that this would not generate some performance issues.

So I did a benchmark!

var count = 10000000;

var MyClass = function(a) {
    this.a = a;
}

MyClass.prototype.foo = function(b) {
    // Do some complex work   
    this.a += Math.cos(b);
    return this;
}

MyClass.prototype.foo2 = function (b) {
    // Do some complex work   
    this.a += Math.cos(b);
}

var start = new Date().getTime();
var obj = new MyClass(5);
obj.foo(1).foo(2).foo(3);
for (var index = 0; index < count; index++) {
    obj.foo(1).foo(2).foo(3);
}
var end = new Date().getTime();

var start2 = new Date().getTime();
var obj2 = new MyClass(5);
for (var index = 0; index < count; index++) {
    obj2.foo2(1);
    obj2.foo2(2);
    obj2.foo2(3);
}
var end2 = new Date().getTime();

var div = document.getElementById("results");

div.innerHTML += obj.a + ": With return this: " + (end - start) + "ms<BR>";
div.innerHTML += obj2.a + ": Without return this: " + (end2 - start2) + "ms";

As you can see foo and foo2 do exactly the same thing. The only difference is that foo can be chained whereas foo2 cannot.

Obviously the call chain is different between:

obj.foo(1).foo(2).foo(3);

and

obj2.foo2(1);
obj2.foo2(2);
obj2.foo2(3);

Given this code, I ran it on Chrome, Firefox and IE to determine if I have to get concerned about performance.

Image 2

And here are the results I got:

  • On Chrome, regular API is 6% slower than fluent API
  • On Firefox, both API are almost running at same speed (fluent API is 1% slower)
  • On IE, both API are almost running at same speed (fluent API is 2% slower)

The thing is that I added an operation into the function (Math.cos) to simulate some kind of treatment done by the function.

If I remove everything and just keep the "return" statement, on all browser there is no difference (actually just one or two milliseconds for 10,000,000 tries). You can test this for yourself across the browsers. And if you don’t have the devices handy, there are plenty of free tools on dev.modern.IE. Just don’t perf test a virtual machine against a real device. :)

Image 3

So my conclusion is: It’s a go!

Fluent API is great, it produce more readable code and you can use it without any problem or performance loss!

More hands-on with JavaScript

It might surprise you a bit, but Microsoft has a bunch of free learning on many open source JavaScript topics and we’re on a mission to create a lot more with Microsoft Edge coming. Check out my own:

Or our team’s learning series:

And some free tools: Visual Studio Community, Azure Trial, and cross-browser testing tools for Mac, Linux, or Windows.

This article is part of the web dev tech series from Microsoft. We’re excited to share Microsoft Edge and the new EdgeHTML rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device @ http://dev.modern.ie/.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
David Catuhe is a Principal Program Manager at Microsoft focusing on web development. He is author of the babylon.js framework for building 3D games with HTML5 and WebGL. Read his blog on MSDN or follow him @deltakosh on Twitter.

Comments and Discussions

 
PraiseMy vote of 5 Pin
Liju Sankar7-Dec-15 17:02
professionalLiju Sankar7-Dec-15 17:02 
My vote of 5
-- Dev 007

GeneralMy vote of 5 Pin
Prasad Khandekar15-Jun-15 21:07
professionalPrasad Khandekar15-Jun-15 21:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.