Wednesday, May 29, 2013

Excerpts from Google IO 2013 - Drilling down on performance! - Device Agnostic Development

Excerpts from Google IO 2013 - Drilling down on performance!
  • Its is seen that support for desktop is 96%, phone 68% & tablet 69%.
  • And prioritisation for desktop is 81%, phone 12% & tablet is 7%.
Today web is being consumed by different devices.
According to the grand unified theory of devices, the delay factor can come into existence in the following areas - 
  1. Network
  2. Compute
  3. Render
Device Vs Constraints :
With respect to the available devices and contraints for the same, framerate has to be maintained at 60 fps.
We would need solving for the below areas -
Solving for network :
  • Reduce page load time - PLT
 >3 secs, 57% of the users go away.
 46% will not return out of these.
 22% will tell their contacts not to use this website.
  •  So on the average 1 in 5 will tell their contacts not to use the site.
  • Reduce your requests
  • Latency, bandwidth and financial cost.
  • Remove any requests which are obsolete or not required : do you really need that file?
  • Concatenate and minify
  • 60% of web traffic is images - change formats, request the size that is required for the page or fits the page & SVG/ web fonts might be a better option.
  • Mod_pagespeed plugin.
  • Use page speed insights to analyse and suggest optimisations to the page
  • Use resource timing api.
Solving for compute:
  • Jank - 60 Hz framerate allows 16.7 milliseconds to get everything done - called as - frame budget.
  • Limit style recalculations
  • Don't change the body when you should change child elements directly.
  • Limit style changes to DOM.
  • Avoid layout thrashing - asking for offset fit requires a layout calculation, multiple get(s)/set(s) will increase the cost - should be get once and use at all places.
  • Remove unnecessary JS - don't do in JS that which can be done in CSS - animations and one transitions.
  • Keep position : fixed or position : sticky.
  • Keep your event listener code to a minimum - they can run several times per frame - store the scroll value of the last operation and keep that one value for one handler approach.
Solving for render:
  • Typical page shows around 13 ms for processing images and 70ms to image resize rendering time - objective should be getting smallest possible image in the correct dimensions to avoid resizing.
  • Paint costs - scroll that corresponds to entire page getting repainted
  • 'enable continuous page' painting in chrome settings and check out the css element adding to the cost.
Suggestions:
  • Assess performance constraints before you start
  • Set limits- eg : no of requests, GCs, paint time, layout, style calculations.
  • Track during project lifetime.
  • Don't ship until you hit your targets.
Additional tip for different devices:
Give them the same content but refactor for the constraint.
Sites for more information:
Use Jankfree.org for more details.

Monday, May 27, 2013

Thinking ahead - Google drive integration with app script!


Thinking ahead - Google drive integration with app script!
A bit of a background
What is google drive?
 Google drive is a file storage and synchronisation service provided by Google launched in April 2012. It enables user cloud storage, file sharing and collaborative editing.
What is a google app script?
 Google app script is a JavaScript cloud scripting language that lets you extend Google Apps and build web applications. Scripts are developed in Google Apps Script's browser-based script editor, and they are stored in and run from Google's servers.
How to integrate?
 Two essential integration flows.
  • Having your application available to the users in google drive.
  • Access files in Google drive from google app script.
 The steps to integrate via an illustrated example are given below :
 Step 1 : Create a roster in google spread sheet.
 Step 2 : Open up Google drive and go to 'my drive'.
 Step 3 : Open up the link in the mail pointing to the application developed.
 Step 4 : Page redirected to a welcome screen for installation of the Google App for proceed  confirmation.
 Step 5 : Post installation refresh the drive contents and this app would be visible in the list of your installed apps.
 Step 6 : Click on the application to start it.
 Step 7 : After application completes the run, the contents created by the application should be visible in the google drive.
 Step 8 : The created docs can be worked upon and saved.
 Step 9 : Options in the application provide you with the information for next steps like for eg: publish, so that the application is visible to selected people in the google drive n/w.
 Step 10 : A person with the persona of student would be able to view the published contents on their login and act on the same.
 Step 11 : A time slot is given to users to act on the contents of the created docs and then the quiz is closed and any attempts to save the information further by people or group working on it would be restricted with a user friendly message.

What are Key concepts : App script & google drive
  • App script works on google drive and also provides ability to call external services via apis.
  • Code can be written in a browser using the url script.google.com.
  • The code script goes as part of the app and provides all the functions for it.
  • The editor is equipped with basic editor functionality along with auto complete feature.
  • Also google app script apps can be deployed as a web application.
  • Works on exposing web end points for the business logic.
  • Deploy and run the application as end user rater than developer the developed it.
  • Restrict and control access to the app for a particular domain.
  • Implement a method called doGet based on servlet programming and return the contents post processing.
What are salient features of Google drive sdk?
  • Integrate with drive UI.
  • Build web application by the above process.
  • Install via OAuth 2 drive.install scope for eg: an email link or via Chrome app store.

What is the sdk app lifecycle :
  • Click on the install invokes the web app and introduces a parameter called state.
  • App script kicks off its execution of the business logic and uses drive app Api to read from google drive and write to it.
What are the steps to get the drive sdk integration working?
  • Enable the drive sdk service from developer console in active services of developer console.
  • Click on Drive sdk to get the complete set of settings - important ones are 'open url', 'register default mime types' & 'create with' to let users create documents.
What are the advantages?
  • Linking of two application via google platform and no downloads.
  • Enablement of app being mobile friendly by a single click.
What are nice points about latest drive services?
  • New features - change ownership of file or folder and change default sharing of document to a particular domain.
  • Powerful search functionality & simpler code for receiving files and folders.
What is being restricted as of now on google drive service?
 No longer expose email addresses in order to prevent security lapses. 
PS: All excerpts are taken from Google I/O Sessions 2013 and bundled into an easily understandable structure.

Saturday, May 25, 2013

Gwt latest tweaks, tips and future roadmap from the Google I/O 2013!


Gwt latest tweaks, tips and future roadmap from the Google I/O 2013!


1.When to use the view-presenter model and when to refrain from it?
   Do not use presenter and view separately as long as you have a definate need to do so.
   Its' okay to use a single view if the complexity of design is not more as it reduces overhead.
   Check that the view-presenter model makes good use of the UI Binder.

Rule of the thumb: Start with simplest solution that can work, add complexity only when needed.

2.How to enable testability in rich views?
  Any rich views established should have any logic be put into presenter so as to accomplish testability.
  Its always good to combine the logic, get rid of boiler plate code and place it in the Composite to accomplish easy maintainability.

3.Which testing engine to use for testing GWT implementation?
  Use the mockito to test th GWT implementation.

4.Are GWT apps mobile ready?
  Apps in GWT are mobile ready. One of the primary advantages of the GWT application is that  portability of the app to mobile platform and dynamic reference through nocache.js at run time for performance optimization.

5.What is the role of event bus in MVP architecture?
  EventBus is a global static object inserted into each of the presenters that helps you have
  communication with different nodes of a tree without each node knowing who its talking to.

6.How to design your application for GWT based events?
  Each application has a design tree for functions and certain events that get triggered
  and might be required to cross reference different nodes of separate trees at different levels.
  Decouple your visual hierarchy from the communication model to ease out maintainability.
  In such a scenario its always easy to add code for a new functionality on the event bus and let it   handle the events rather than increase complexity by doing a cross reference by adding code to each node.

7.How to get more details on the event based architecture?
  Check https://github.com/google/gwteventbinder for events.

8.General guideline around design?
  Keep using methods for tightly coupled components in your system. use events wherein notifications are required. 99% of the time events are either user inputs or response coming back from the server. Any extra layer is always harder to optimise but in that case optimisation is not important.

9.What is the future roadmap for GWT?
 1. A separate open community for GWT has been established. There has been a separate GWT website established at www.gwtproject.org
 2. Also GWT code is being maintained by RedHat doing continuous integration at
                build.gwtproject.org and mirroring the same at
        GIT repository
Github - github.com/gwtproject
Source - gwt.googlesource.com
Code Review - gwt-review.googlesource.com
 3. External leaders would be part of Gwt community and driving different browser support and modules for GWT.
 4. Below major areas of focus have been defined for future -
i. Openness and simplicity - Move the complete source to open source, full mavenization of the code build. Reduce the need for .gwt.xml files and delete deprecated code to make lightweight code.
ii.Speed -  improve super dev mode refresh speed, improve code splitter, tune to modern JS VMS & better profiling tools.
iii.Inter-operability - improve support and integration with closure compiler and include java 7 & 8 support.
iv.Mobility - support for modern mobile web browsers, mobile optimized widgets and application lifecycle with offline capability.
v.Reliability - remove support for older browsers and improve gwt unit testing.
vi.Embeddability - pieces of gwt can be embedded in apps.
 5. GWT Compilation speed is aimed to be reduced by 50%.

Wednesday, May 22, 2013

DART – The next step towards optimized JS – HTML of the future!!


DART – The next step towards optimized JS – HTML of the future!!

What is Dart??

 Dart is an open source web programming language developed by Google which appeared in existence in 2011 with latest release M4 in April 16 2013.The goal of dart is 'ultimately to replace JavaScript as the lingua franca of the web development on the open web platform'. Its' a class based, single inheritance, object – oriented language with C-style syntax. It supports interfaces, abstract classes, reified generics, and optional typing. Static type annotations do not affect the runtime semantics of the code.

Where do I see Dart in terms of JS lifecycle on web?

 Traditional JavaScript --> JQuery (optimized feature based JS) --> Dart (Highly optimized, performance intensive, multi-browser, quick development cycle based PL).

 In short it does the job of building an application really quick by using a high end programming language and also does code optimization using tools similar to closure or soy before porting it out for multiple applications. The downside of other tools is long compilation time.

How does it work?
 You develop the program in Dart, Dart uses dartlib and dart2js to convert it to a JavaScript and runs the program in your browser.

Important features of DART?
  • Does not require compilation for development.
  • Eliminates boiler plate code – syntax, sematics and structures
    • Uses named constructers to reduce lines of code.
        eg: Test.namedConstr() : initValue = 100;
    • Operator Overriding
  • Named Optional Parameters
    • eg: void func1({int thisValueIsNeeded: 1})
  • One line funtions & string interpolation
    • eg: String toString() => “This value is $value”;
  • Syntax is similar to normal web programming language like Java.
  • Well defined error messages when a property does not exist – logical errors.
  • Variable scoping follows the principles of a well defined web program.
  • Event based structures are bound to lexical scopes rather than event based object scopes for ease of program understandability.
    • Eg: button.onClick.listen((Event e) => this.checkThisOutItsCool());
    • checkThisOutItsCool() { /*... */ }
  • Structures are inside well defined libraries – you can import libraries and lazy load them as well using metadata.
  • Remove instances of multiple references to a variable when doing property initialization in dom – Method Cascades
    • eg: var button = new ButtonElement();
      • button.id = 'go';
      • button.text = 'Go';
      • button.classes.add('tryme');
      • button.onClick.listen((e) => showTheList());
    • can be written as – (new ButtonElement() ..id='go' ..text='Go' ..classes.add('tryme') ..onClick.listen((e) => showTheList()));
  • Extend objects and compose classes together using behaviors.
  • Metadata – you can define your own metadata
    • eg:you can define a metadata like @lazy load use a future to wait for a library to load.
  • Mirror based proxy elements & reflection– to address and audit third party calls.
    • Eg : mirror = reflect(delegate);
  • Capture and deal with Errors using Future – delegate such calls using mirror instances.
  • Futures has got wait mechanisms to combine waiting on multiple events and then operate on them.
  • Streams – nearly all repeating events in Dart are streams. Also, additionally, we can put filters in streams and perform conversions to map send data in different forms.
  • Enables cross browser compatibility on converted js.
What is required to develop Dart?
 You need the Dart SDK and three packages – Intl, Web UI and Unit Test to run and test Dart programs.

What is needed to Test Dart?
 You can use Dartium : Chromium + Dart VM to test your code and dart2Js to test your code.
Additionally there is a unit test library in Dart to unit test code similar to other web frameworks.

How do I integrate with traditional JavaScript?
The integration with existing JavaScript can be done via JS-Interop using a proxy callback.
Eg: var jsObj = new js.Proxy(api.jsObj1, query('jsObj'));
jsObj.test(input); <-- the access mechanism here is same as JS.

How do I do Asynchronous callbacks using Dart?
Dart provides for asynchronous call back in an elegant way. It reduces traditional call back disadvantages for multiple callbacks using futures and streams.
Eg : Traditional call back – doFunc1(result1) { handle(result1) ; } onError : (e) { handleError(e); });
With Dart futures – Future future = doFunc1();
                                                      future.then(handle);
                                                      future.catchError(handleError);
                                                      doFunc1()
                                                         .then(handle);
                                                         .catchError(handleError);
 The .then clauses can be group in a call back tree to maintain clarity of nesting and understand sequence of callback and maintain the error or exception hierarchy with no additional error handlers.
                                               Eg: x.func(“inp”)
                                                          .then((fun1) => func.getFirst())
                                                         .then((fun2) => func.getSecond())
                                                         .catchError((e) => print(“Something went wrong!”));

What is the impact on Performance when using Dart?
 The impact on performance is critical when using Dart. There is a 'dart2Js' compilation engine which works on the 'tree shaking', ' minification' and 'inferencing' methodologies. The 'tree shaking' curses through the dom tree and find points of optimization, 'minification' – removes blocks of code to reference and utilize less space, 'inferencing' checks the references to remove code not reachable during run time. Also there is a 'Source Map' to enable debugging by mapping Dart code to JavaScript code for debugging.

 The performance reduction has been measured at 2wice the savings using desktop and 2wice the savings using mobile or handheld gadgets based on x86 architectures.
You can reference - http://www.dartlang.org/performance/ for more details.

How can I see live Dart code or see a visual demo?
 You can use 'try.dartlang.org' to check how a dart code would run in the UI. You can try on different web browser engines and tablet devices like iPad.

Can I download and manage updates to packages for Dart?
 Yes you can reference this site 'pub.dartlang.org' and this support various version management tools like git, virtual file system, etc.


PS : The above details have been taken from Google I/O 2013 sessions and compiled into usability driven questionnaire.