Community, Javascript

What ES6 features can be used in Node with no transpiler [Part 2]

Let’s continue our investigation on what ES6 features are available today (v4.1.0) in Node.
In part 1 we covered block scoping variables  and Classes, in this post we’ll cover collections.

Collections

A good way to start understanding collections in ES6 is reading this great post on hacks.mozilla.org from Jason Orendorff.

Map

Here’s a true game changer. Map makes decoupled object-to-object association finally possible in javascript.
As stated in the reference docs “Objects have been used as Maps historically”, but it’s really important we have clear the difference between Map and Object.
While Objects can only map literals to values, with Map can associate value to value.

Benefits

Let me play the role of Capitan Obvious and say it again: we can now associate objects to objects with no string involved.map association example

Other builtin perks are:

  • size  and clear come for free, so we don’t have to keep our own counter as a property (and then to exclude it from the count itself…).
  • NaN uniqueness , even if NaN === NaN is false, we can use NaN as a unique key
  • iterators (entries, values, keys) and a handy forEach method
  • has(key) replacing the quirky hasOwnProperty method to check if a key is present

Set

A Set is a collection of non duplicate values.

Benefits

The main benefit provided by Set is exactly the main purpose it was designed for: filtering out duplicate objects.
I would bet (too) many times we have found ourselves writing code like the following in order not to add twice the same value to an array…

Screen Shot 2015-10-07 at 19.55.18

… or even to an object…

Screen Shot 2015-10-07 at 19.55.29

And we found out that, unless we put in place a hashing algorithm, or our collection allowed us to use a binary search, we ended up with a linear lookup time that may be not good enough as our collection grows.

Set solves this providing constant lookup time out of the box, and a simple API.

Screen Shot 2015-10-07 at 19.55.37

Check yourself this little benchmark, you will notice the difference as the collection grows. (Run it with: “node <filename> <elements amount> <iterations amount>”).

On top of its main purpose, Set comes with several handy utility methods (similar to Map btw…) such as entries, keys and values (keys and values are the SAME function!!!) iterators, size\clear, has to check if the set contains a given value, and the usual forEach.

WeakMap and WeakSet

I’m grouping these up as we already covered Map and Set individually and these two variants of those data structures are very similar to each other.

WeakMap or WeakSet don’t hold a strong reference to the objects they store, hence if the only existing reference to an object is stored in one of these collections the GC will kill it and free that memory location as it passes.

To get a better understanding of garbage collection in take a look to the examples in the reference docs.

Benefits

When coming to the benefits these weak collections come with, the typical usecase we will stumble upon is about keeping a reference to a DOM object without impeding the GC from collecting it. Even if that gives us an idea of the functionality, it doesn’t fit well to Node.

An example sitting better in this context could be filtering existing collections without keeping a strong reference to each element of the original collection. Consider the following code:

Screen Shot 2015-10-07 at 22.07.29

What next?

Part 3 will come soon! Watch this space 😉

Community, Javascript

What ES6 features can be used in Node with no transpiler [Part 1]

As soon as I started attending the great London JS community meetups I immediately noticed mixed feelings around ES6.
It seems people is definitely looking forward to it becoming mainstream and they’re hungry for information about it, but at the same time they tend to stand clear of it in production.
Skepticism? Lack of success stories? maybe…
At the time of writing ES6 is not fully supported everywhere and our code needs to be transpiled to older versions of Javascript in order to run properly on all the targets.
Hence, where ES6 is not supported the code we wrote is NOT what gets executed, and all the new cool features provided by ES6 become mere syntactical sugar that comes at a high potential cost:

  • bugs\incompatibilities difficult to debug (as, again, the code we wrote is not the code that is executed)
  • performance issues difficult to overcome (as a new performance enhancement can be transformed in a not-so-performing piece of “old” javascript)

I can imagine some pioneers’ smirk right now. Yes we can run our node app using the ES6 staged features, or even the features currently under development, but is it really a choice? Are we confident enough to run our production app on a beta (or even alpha depending on the maturity of the single feature we plan to toggle) ?

So, let’s consider the bright side for a minute…
Last time I checked the Node docs I read that some ES6 features are ALREADY supported with NO RUNTIME FLAG REQUIRED.
So, I would not go for yet another post on how to fake… ehm…”transpile” ES6 in your Node project, nor I would suggest you to enable all the WIP features.
I’d rather check what is possible to use AS TODAY in Node (version 4.1.0), and identify what are the benefits they come with.

Our trip is going to be long, so let’s start from listing what is available from the menu:

  • Block scoping
    • let
    • const
  • Classes
  • Collections
    • Map
    • WeakMap
    • Set
    • WeakSet
  • Typed arrays
  • Generators
  • Binary and Octal literals
  • Object Literal extensions
  • Promises
  • New String methods
  • Symbols
  • Template strings
  • Arrow functions

Block scoping

let & const

These new features are real game changers (even if you are a “var” aficionado).
While the memory allocated by var lives within the function scope, the memory allocated by let and const lives within the code block.

Benefits

Syntax sugar aside, a much more granular memory management is VERY welcome.
Before ES6, each time a var was declared a memory location was kidnapped for the entire function scope.
Check the examples in the reference docs, but also consider this example using files and repeat with me: “yes, my app won’t be memory hungry anymore”.
Screen Shot 2015-09-30 at 21.45.47

Classes

As the docs reads Classes “are syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript.”

Benefits

Syntax sugar, no memory management nor performance benefits.

Where are the others?!

Read Part 2 to get some insight about ES6 collections!

Community, Haxe

WWX 2014 follow up – thoughts on haxe

I just came back from the World Wide haXe conference held in Paris this weekend and want to share my thoughts.

I’ve been evaluating haxe as a viable option for my company’s daily development other times in the past as I really think the language is great and the technology has a huge potential.
What always made me choose for a different solution was the lack of tools, the focus on the gaming industry, and the lack of documentation.
So I left for Paris with a defined set of questions and got a range of answers from very disappointing to mind blowing.

Let’s start with the good news, and let’s talk about

Case histories

what to say… I’ve been mind blown, two huge success stories and both OUT  of the gaming industry.

Documentation

The haxe foundation (finally) decided to focus on documentation and rolled out

Tooling

I’ve been VERY bothering throughout the whole conference about tooling, I asked almost all speakers about the tools they used in the daily development.
Coming from 5 years across IntelliJ, Visual Studio, Xcode and Eclipse I feel the need for a major IDE and a working automated build pipeline for my technology of choice.

I got quite disappointed by the choice of the haxe foundation to focus the effort in sponsoring yet another haxe IDE , only for haxe development, namely HIDE https://github.com/as3boyan/HIDE, instead of focusing on a major IDE support.
I got even more disappointed when more and more speakers and attendees were trivialising what I felt as a major issue and were pointing out that sublime text is simply “good enough”.
Luckily business stories are choosing a different approach and both TiVo and Prezi showed they’re using intellij for development, and the guys from TiVo said that the work to be done on that plugin is still quite a lot, for instance there’s no unit test runner.
Tools are far from being at the level of other languages, but luckily all of them are open source and can be improved by the community, and at the time writing it is possible do what a mature language environment should allow:

Even if the road is still uphill we can spot the top getting nearer.

Other news

More news were presented, briefly:

  • there’s a brand new python target
  • it’s now possible to script Unity from haxe, thanx https://twitter.com/cwaneck
  • there’s plenty of new libs and macros https://github.com/jdonaldson/promhxhttps://github.com/ciscoheat/haxedci  are just few
  • an interesting “twisted” point of view of “haxe as compiler target” bubbled up from the community in the person of https://twitter.com/ElliottStoneham
  • new version of OpenFL (even though it wasn’t presented at the conference it’s worth mentioning) 
  • NME is still alive! I thought NME became OpenFL but they’re just two different projects and now the haxe foundation is trying to merge the effort of the two teams
  • Date and String encoding issues are the next thing to fix in the TODO list of Haxe for the upcoming year
  • short lambdas!!! (no, just kidding)

here’s the link to the slides of the keynote http://ncannasse.github.io/hxslides/www/wwx2014.html

Conclusion

I had good time in Paris, got answers to all of my questions and I came back thinking Haxe is a viable option for a business, even if tools are still quite not there the power of the technology is worth enough to give it a shot.
If I had to set a TODO list for haxe it would look like this:

  • fix language problems on String encoding and Date object
  • focus on getting BIG PLAYERS involved, hire a CEO, move to the US. Exit the startupper garage and think big.
  • focus on tools:
    • intellij plugin experience should be near to java\as3
    • maven mojo is still behind
    • focus on conversion tools from * to Haxe (TiVo moved to haxe also because most of the “dirty job” was automated)
  • focus on community: encourage the creation of user groups in key locations

Last but not least, once again I was very impressed by the vibrant community that drives this technology, thank you all guys for your effort to make this technology grow better and better, and a special thanx the whole crew of SilexLabs to have organized the event.

Anything else, Community, Tutorials

Creating and Managing Flash Enterprise Projects – VOTE FOR ME!!!

I just submitted my idea for a book to Packt Publishing.
One of the main lack I see in the panorama of flash books is all about industrializing projects. There are fewno books about coding conventions, code management, environment setup, code reutilization, unit testing, ecc ecc… and a plenty of “making (little) games with flash”, “using (basic) 3d with flash”, etc.

The idea I submitted is called “Creating and Managing Flash Enterprise Projects”.
My plan is to talk about how to setup and maintain an enterprise level project built over the flash platform… if you like such an idea, please vote for me here >>>> http://t.co/2xxmchp

thanx,
ciao 😉

ActionScript 3, Community, Speaking, Tutorials, Uncategorized

FlashCamp Milan 2011 – Garbage Collection in the Flash Platform

This post is to summarize my session at the FlashCamp.

Here’s the preso: (italian only)

and here are the examples shown during the session:

Garbage collector in action:
this example shows the memory allocation behavior. Take a look to the saw tooth yellow line in the graph.

Weak vs Strong references:
two examples to show the difference between weak and strong references: basically weak do not increment reference count, strong do that.
If you store keys in a dictionary using weak references your keys are getting cleaned by the garbage collector ( example )
otherwise the GC doesn’t clean your keys ( example ).

Blitting in order to ease the GC:
The GC iterates through each reachable node starting from the roots, one of these roots is the displaylist. So in order to ease the GC work we could flatten the whole displaylist to one bitmap by leveraging the usage of the blitting technique.
These examples display about 1000 new objects drawn each frame by using the display list ( example ) or the blitting technique ( example ). The difference in performances are not only due to the different compositing techniques (built in compositing when using the displaylist VS manual compositing when using the blitting technique ) but also to the lower number of instances to be collected by the GC.

NOTE: both examples are very cpu intensive

Don’t let the GC start by using the memory pool technique:
The GC freezes the program when freeing the memory. The memory pool technique consists in reusing the instances of your objects preventing the GC to identify those objects as garbage.
This makes your app memory utilization stable (a straight yellow line ) and removes every glitch due to the garbage collection.
These examples show a simple particle fountain implemented by leveraging the memory pool technique ( example ) or not ( example ).

Finally:
here’s the source, it’s not the best commented nor the best implemented files out there, but just take a look at them to have a full comprehension of what’s going on 😉

If you need further help, please comment this post and let me know.
ciao

PS: obviously mario copyright is property of nintendo 🙂