SlideShare a Scribd company logo
Mobile Optimization
Jesse MacFadyen
Optimus Prime


"More computing sins are committed in the name of
efficiency (without necessarily achieving it) than for any
other single reason — including blind stupidity." —
W.A. Wulf
About Me


With Nitobi for the last 3 years
Built many large scale JS Apps for Mobile devices.
PhoneGap contributor ( iOS + WP7 )
What is Optimization?
2 Categories
Time vs Space
- Balance is the key.
When should you optimize?



When you notice
performance lag
Often, each iteration
Review at the end
of each release
cycle
What to optimize

It has been said that when an application is running,
    90% of the time is spent in 10% of the code.

                   Find the 10%
Benchmarking
It is hard to judge improvement without measurement.


     console.log("running test 1")
     var startTime = new Date().getTime();

     /// lots of looping in here

     var elapsed = new Date().getTime() - startTime;
     console.log("Test 1 took : " + elapsed);
A quick demo.
What does this tell us?
  Run your loops a lot!
  Be somewhat realistic
  If it ain't broke, don't fix it!
Know when to optimize


  function doIt(a,b,c,d,e)
  {
      if(typeof a === "function")
      {
           a(b,c,d,e);
      }
      else
      {
           throw "wtf?";
      }
  }
Minification


 There are tools for that
 This is an extreme example, but it happens.
 Trust me.
 Add a minification tool to your build process.
Minification Tools
  JSMin
    http://www.crockford.com/javascript/jsmin.html
  YUI Compressor
    http://developer.yahoo.com/yui/compressor/
  Closure
    http://code.google.com/closure/


Minification does not improve execution time of your code!
More Tools - Quality


 JSLint, by Douglas Crockford
   http://www.jslint.com/
 JSHint, based on JSLint
   http://www.jshint.com/
Concatenation

 Combining multiple input files into a single file
 request can help with load times as well.
 PhoneGap uses this technique for the JS code
 in phonegap.js.
More coding tips :


 Dereference long
 variables
 or frequently used
 variables with a local
 alias.
Long object reference

ex. ( Bad )
function findUserById(id)
{
  for(var n = 0; n < app.model.userInfo.contacts.length; n++)
  {
      if(app.model.userInfo.contacts[n].id === id)
      {
        return app.model.userInfo.contacts[n];
      }
  }
}
Dereferenced Object Alias
ex. ( Better )

function ndUserById(id)
{
  var contacts = app.model.userInfo.contacts;
  for(var n = 0, len=contacts.length; n < len; n++)
  {
    if(contacts[n].id === id)
    {
       return contacts[n];
    }
  }
}
What really happens with
 long object chains:
Because we store a local alias to the contacts array, we
don't have to dereference repeatedly.

app.model.userInfo.contacts


find a var named 'app'
find a property named 'model'
find a property named 'userInfo'
find a property named 'contacts'
Using the right container
-- assuming ids are unique in the
contacts list :

function findUserById(id)
{
    // no searching ...
    return
app.model.userInfo.contacts[id];
}
// and when we received them from the server, we probably
// got them like this:

// Bad?
function onServerResult(res)
{
    for(var n = 0; n < res.length; n++)
    {
        var contact = JSON.parse(res[n]);
        app.model.userInfo.contacts[contact.id] = contact;
    }
}
// what about lifting?
// that's better
function onServerResult(res)
{
    var contacts = app.model.userInfo.contacts;
    var contact;
    for(var n = 0; n < res.length; n++)
    {
        contact = JSON.parse(res[n]);
        contacts[contact.id] = contact;
    }
}
Switch vs If/Else


Demo of an extreme case
Switch on Boolean
// validate a form

switch(true)
{
  case ( usernameTxt.value == null) :
    // set error message, set focus, ...
    return false;
  case ( passwordTxt.value == null) :
    return false;
  case ( passwordTxt.value != password2Text.value)
    return false;
}

Always put your most likely cases rst, to avoid extra processing.
Exit as soon as possible, if you found it, then stop looking.
Key questions to ask
Is the performance really that bad?
Perception is key.
Does your app remain responsive?
var processedIndex = 0;
var jobs = [];

function processNextValue()
{
  if(processedIndex < jobs.length)
  {
     doJob(jobs[processedIndex++]);
     setTimeout(processNextValue,1);
  }
}

function doJob(job)
{
  // assume some short bit of work here
}

function onTouchStart(e)
{
  // you could even pause your processing in here
}

function onCancelButton(e)
{
  // cancel your jobs
}
On to the DOM
The DOM is your friend, be nice to it!
A common performance
killer is this nasty tidbit :

  for(var n = 0; n < results.length; n++)
  {
    var elementMarkup = "<li class='resultItem'>" + results[n] + "</li>";
    document.getElementById("resultList").innerHTML += elementMarkup;
  }
Prepare your updates to the
    DOM

var elementsMarkup = "";
for(var n = 0; n < results.length; n++)
{
   elementsMarkup += "<li class='resultItem'>" + results[n] + "</li>"
}
document.getElementById("resultList").innerHTML += elementsMarkup;



 Now we are only modifying the DOM once, and it can
                be updated quickly.
DOM best practices
 if you can avoid using css gradients, then drop them.
 They are heavy to render, especially in scrolling lists.
 avoid transparency where possible. If an item is
 transparent, the stuff behind it needs to be rendered too.
 use 3D transforms for moving/sliding DOM elements.
 Most newer devices use hardware acceleration for 3D
 transforms. Essentially you will just throw away the Z.
ex.
Slide right :
element.style.webkitTransitionDuration = "600ms";
element.style.webkitTransform = "translate3D(-320px,0px,0px)";

An example of this later.
Sprite Sheets
Instead of loading many small icons, or UI elements as
separate images, consider compositing them into one
image file and using css properties to manipulate what
area is shown.
http://www.tutorial9.net/tutorials/web-tutorials/building-
faster-websites-with-css-sprites/
And there are tools to help you.
http://spritegen.website-performance.org/
... many out there, look around.
Using Libraries
 There are millions out there! ( okay, hundreds )
 Most will work with PhoneGap
 jQuery Mobile - the big name
 Sencha Touch - rich interaction
 Dojo Mobile
 XUI - Nitobi’s own
 - Nitobi's own
Do you need a UI framework?
 You may not need a full blown UI Framework, there are
 also lighter options to consider.
 Backbone.js gives you a nice scaffold, and helpers for
 managing your app.
 Underscore.js is JS utility belt, helpers for function
 binding, ...
That elusive scrolling
iScroll4

My favorite scrolling library ( even over my own )
A very common request, how do we make some things scroll,
while other things don't?

iScroll works with iOS and Android, and has no
dependancies.
Follow a few simple rules, and you can have nice scrolling
content with scrollbars.
Ekiben Demo
open source MIT
  in github/purplecabbage/ekiben
General Considerations
follow MVC conventions, and keep a clear separation
between the views of your app.
keep things async, and try to implement
eventListeners, or some notification system.
scripts at the bottom!
More Crazy Goodness
// Write your own query selector
function $(query)
{
	 return document.querySelectorAll(query);
}



More here :
http://cubiq.org/do-you-really-need-jquery-for-mobile-dev
Function.prototype.bind = function(sub)
{
   var me = this;
   return function(){ return me.apply(sub, arguments);};
};

Just call like this :

someObject.myFunk = function()
{
  // this is this of someObject
}

someObject.doLater = function()
{
  setInterval( this.myFunk.bind(this),1000);
}

More Related Content

What's hot

Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
AngularJS best-practices
AngularJS best-practicesAngularJS best-practices
AngularJS best-practicesHenry Tao
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJSRan Mizrahi
 
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 -  Fullstack end-to-end Test Automation with node.jsForwardJS 2017 -  Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.jsMek Srunyu Stittri
 
Javaland 2017: "You´ll do microservices now". Now what?
Javaland 2017: "You´ll do microservices now". Now what?Javaland 2017: "You´ll do microservices now". Now what?
Javaland 2017: "You´ll do microservices now". Now what?André Goliath
 
Das kannste schon so machen
Das kannste schon so machenDas kannste schon so machen
Das kannste schon so machenAndré Goliath
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript MisunderstoodBhavya Siddappa
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
Von JavaEE auf Microservice in 6 Monaten - The Good, the Bad, and the wtfs...
Von JavaEE auf Microservice in 6 Monaten - The Good, the Bad, and the wtfs...Von JavaEE auf Microservice in 6 Monaten - The Good, the Bad, and the wtfs...
Von JavaEE auf Microservice in 6 Monaten - The Good, the Bad, and the wtfs...André Goliath
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with WingsRemy Sharp
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected JourneyUI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected JourneyOren Farhi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBApaichon Punopas
 

What's hot (20)

Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
AngularJS best-practices
AngularJS best-practicesAngularJS best-practices
AngularJS best-practices
 
ReactJS
ReactJSReactJS
ReactJS
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
 
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 -  Fullstack end-to-end Test Automation with node.jsForwardJS 2017 -  Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
 
Javaland 2017: "You´ll do microservices now". Now what?
Javaland 2017: "You´ll do microservices now". Now what?Javaland 2017: "You´ll do microservices now". Now what?
Javaland 2017: "You´ll do microservices now". Now what?
 
Das kannste schon so machen
Das kannste schon so machenDas kannste schon so machen
Das kannste schon so machen
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Von JavaEE auf Microservice in 6 Monaten - The Good, the Bad, and the wtfs...
Von JavaEE auf Microservice in 6 Monaten - The Good, the Bad, and the wtfs...Von JavaEE auf Microservice in 6 Monaten - The Good, the Bad, and the wtfs...
Von JavaEE auf Microservice in 6 Monaten - The Good, the Bad, and the wtfs...
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected JourneyUI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected Journey
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile Services
 
Web workers
Web workersWeb workers
Web workers
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 

Similar to Mobile optimization

Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptdavejohnson
 
Building with JavaScript - write less by using the right tools
Building with JavaScript -  write less by using the right toolsBuilding with JavaScript -  write less by using the right tools
Building with JavaScript - write less by using the right toolsChristian Heilmann
 
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP AnywayI Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP AnywayAll Things Open
 
Optimizing Apps for Better Performance
Optimizing Apps for Better PerformanceOptimizing Apps for Better Performance
Optimizing Apps for Better PerformanceElif Boncuk
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJSGregor Woiwode
 
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP AnywayI Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP AnywayPOSSCON
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentationMennan Tekbir
 
Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Clarence Ngoh
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day trainingTroy Miles
 
BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!Craig Schumann
 
The State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistThe State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistMark Fayngersh
 
...and thus your forms automagically disappeared
...and thus your forms automagically disappeared...and thus your forms automagically disappeared
...and thus your forms automagically disappearedLuc Bors
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core ConceptsDivyang Bhambhani
 
Story about module management with angular.js
Story about module management with angular.jsStory about module management with angular.js
Story about module management with angular.jsDavid Amend
 
Building Rich User Experiences Without JavaScript Spaghetti
Building Rich User Experiences Without JavaScript SpaghettiBuilding Rich User Experiences Without JavaScript Spaghetti
Building Rich User Experiences Without JavaScript SpaghettiJared Faris
 

Similar to Mobile optimization (20)

Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
 
Building with JavaScript - write less by using the right tools
Building with JavaScript -  write less by using the right toolsBuilding with JavaScript -  write less by using the right tools
Building with JavaScript - write less by using the right tools
 
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP AnywayI Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
 
Optimizing Apps for Better Performance
Optimizing Apps for Better PerformanceOptimizing Apps for Better Performance
Optimizing Apps for Better Performance
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJS
 
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP AnywayI Know It Was MEAN, But I Cut the Cord to LAMP Anyway
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Xam expertday
Xam expertdayXam expertday
Xam expertday
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentation
 
Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day training
 
BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!
 
The State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistThe State of Front-end At CrowdTwist
The State of Front-end At CrowdTwist
 
...and thus your forms automagically disappeared
...and thus your forms automagically disappeared...and thus your forms automagically disappeared
...and thus your forms automagically disappeared
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
Story about module management with angular.js
Story about module management with angular.jsStory about module management with angular.js
Story about module management with angular.js
 
Mean stack Magics
Mean stack MagicsMean stack Magics
Mean stack Magics
 
Building Rich User Experiences Without JavaScript Spaghetti
Building Rich User Experiences Without JavaScript SpaghettiBuilding Rich User Experiences Without JavaScript Spaghetti
Building Rich User Experiences Without JavaScript Spaghetti
 

Recently uploaded

PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Thierry Lestable
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaRTTS
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsVlad Stirbu
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀DianaGray10
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform EngineeringJemma Hussein Allen
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
 

Recently uploaded (20)

PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 

Mobile optimization

  • 2. Optimus Prime "More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason — including blind stupidity." — W.A. Wulf
  • 3. About Me With Nitobi for the last 3 years Built many large scale JS Apps for Mobile devices. PhoneGap contributor ( iOS + WP7 )
  • 5. 2 Categories Time vs Space - Balance is the key.
  • 6. When should you optimize? When you notice performance lag Often, each iteration Review at the end of each release cycle
  • 7. What to optimize It has been said that when an application is running, 90% of the time is spent in 10% of the code. Find the 10%
  • 8. Benchmarking It is hard to judge improvement without measurement. console.log("running test 1") var startTime = new Date().getTime(); /// lots of looping in here var elapsed = new Date().getTime() - startTime; console.log("Test 1 took : " + elapsed);
  • 10. What does this tell us? Run your loops a lot! Be somewhat realistic If it ain't broke, don't fix it!
  • 11. Know when to optimize function doIt(a,b,c,d,e) { if(typeof a === "function") { a(b,c,d,e); } else { throw "wtf?"; } }
  • 12. Minification There are tools for that This is an extreme example, but it happens. Trust me. Add a minification tool to your build process.
  • 13. Minification Tools JSMin http://www.crockford.com/javascript/jsmin.html YUI Compressor http://developer.yahoo.com/yui/compressor/ Closure http://code.google.com/closure/ Minification does not improve execution time of your code!
  • 14. More Tools - Quality JSLint, by Douglas Crockford http://www.jslint.com/ JSHint, based on JSLint http://www.jshint.com/
  • 15. Concatenation Combining multiple input files into a single file request can help with load times as well. PhoneGap uses this technique for the JS code in phonegap.js.
  • 16. More coding tips : Dereference long variables or frequently used variables with a local alias.
  • 17. Long object reference ex. ( Bad ) function findUserById(id) { for(var n = 0; n < app.model.userInfo.contacts.length; n++) { if(app.model.userInfo.contacts[n].id === id) { return app.model.userInfo.contacts[n]; } } }
  • 18. Dereferenced Object Alias ex. ( Better ) function ndUserById(id) { var contacts = app.model.userInfo.contacts; for(var n = 0, len=contacts.length; n < len; n++) { if(contacts[n].id === id) { return contacts[n]; } } }
  • 19. What really happens with long object chains: Because we store a local alias to the contacts array, we don't have to dereference repeatedly. app.model.userInfo.contacts find a var named 'app' find a property named 'model' find a property named 'userInfo' find a property named 'contacts'
  • 20. Using the right container -- assuming ids are unique in the contacts list : function findUserById(id) { // no searching ... return app.model.userInfo.contacts[id]; }
  • 21. // and when we received them from the server, we probably // got them like this: // Bad? function onServerResult(res) { for(var n = 0; n < res.length; n++) { var contact = JSON.parse(res[n]); app.model.userInfo.contacts[contact.id] = contact; } }
  • 22. // what about lifting? // that's better function onServerResult(res) { var contacts = app.model.userInfo.contacts; var contact; for(var n = 0; n < res.length; n++) { contact = JSON.parse(res[n]); contacts[contact.id] = contact; } }
  • 23. Switch vs If/Else Demo of an extreme case
  • 24. Switch on Boolean // validate a form switch(true) { case ( usernameTxt.value == null) : // set error message, set focus, ... return false; case ( passwordTxt.value == null) : return false; case ( passwordTxt.value != password2Text.value) return false; } Always put your most likely cases rst, to avoid extra processing. Exit as soon as possible, if you found it, then stop looking.
  • 25. Key questions to ask Is the performance really that bad? Perception is key. Does your app remain responsive?
  • 26. var processedIndex = 0; var jobs = []; function processNextValue() { if(processedIndex < jobs.length) { doJob(jobs[processedIndex++]); setTimeout(processNextValue,1); } } function doJob(job) { // assume some short bit of work here } function onTouchStart(e) { // you could even pause your processing in here } function onCancelButton(e) { // cancel your jobs }
  • 27. On to the DOM The DOM is your friend, be nice to it!
  • 28. A common performance killer is this nasty tidbit : for(var n = 0; n < results.length; n++) { var elementMarkup = "<li class='resultItem'>" + results[n] + "</li>"; document.getElementById("resultList").innerHTML += elementMarkup; }
  • 29. Prepare your updates to the DOM var elementsMarkup = ""; for(var n = 0; n < results.length; n++) { elementsMarkup += "<li class='resultItem'>" + results[n] + "</li>" } document.getElementById("resultList").innerHTML += elementsMarkup; Now we are only modifying the DOM once, and it can be updated quickly.
  • 30. DOM best practices if you can avoid using css gradients, then drop them. They are heavy to render, especially in scrolling lists. avoid transparency where possible. If an item is transparent, the stuff behind it needs to be rendered too. use 3D transforms for moving/sliding DOM elements. Most newer devices use hardware acceleration for 3D transforms. Essentially you will just throw away the Z. ex. Slide right : element.style.webkitTransitionDuration = "600ms"; element.style.webkitTransform = "translate3D(-320px,0px,0px)"; An example of this later.
  • 31. Sprite Sheets Instead of loading many small icons, or UI elements as separate images, consider compositing them into one image file and using css properties to manipulate what area is shown. http://www.tutorial9.net/tutorials/web-tutorials/building- faster-websites-with-css-sprites/ And there are tools to help you. http://spritegen.website-performance.org/ ... many out there, look around.
  • 32. Using Libraries There are millions out there! ( okay, hundreds ) Most will work with PhoneGap jQuery Mobile - the big name Sencha Touch - rich interaction Dojo Mobile XUI - Nitobi’s own - Nitobi's own
  • 33. Do you need a UI framework? You may not need a full blown UI Framework, there are also lighter options to consider. Backbone.js gives you a nice scaffold, and helpers for managing your app. Underscore.js is JS utility belt, helpers for function binding, ...
  • 34. That elusive scrolling iScroll4 My favorite scrolling library ( even over my own ) A very common request, how do we make some things scroll, while other things don't? iScroll works with iOS and Android, and has no dependancies. Follow a few simple rules, and you can have nice scrolling content with scrollbars.
  • 35. Ekiben Demo open source MIT in github/purplecabbage/ekiben
  • 36. General Considerations follow MVC conventions, and keep a clear separation between the views of your app. keep things async, and try to implement eventListeners, or some notification system. scripts at the bottom!
  • 37. More Crazy Goodness // Write your own query selector function $(query) { return document.querySelectorAll(query); } More here : http://cubiq.org/do-you-really-need-jquery-for-mobile-dev
  • 38. Function.prototype.bind = function(sub) { var me = this; return function(){ return me.apply(sub, arguments);}; }; Just call like this : someObject.myFunk = function() { // this is this of someObject } someObject.doLater = function() { setInterval( this.myFunk.bind(this),1000); }

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n