SlideShare a Scribd company logo
Appcelerator Titanium Mobile

                  FLEXIBILITY
                  VS
   PERFORMANCE
Olivier Morandi
$ whoami
    Olivier Morandi
    Software engineer

      http://titaniumninja.com
      olivier.morandi@gmail.com
      @olivier_morandi
      https://github.com/omorandi


2           Appcelerator Titanium - Flexibility vs. Performance
Titanium Mobile
    • Rapid development & prototyping tool
    • Single high level language: JS
    • Multiple deployment platforms (iOS, Android, ...)
    • We can leverage an ever growing set of JS
      libraries and modules (web, node.js, etc.)
    • Possibility to extend the framework with native
      modules


3             Appcelerator Titanium - Flexibility vs. Performance
Titanium Apps are NATIVE




    Can we also expect a native User Experience?




4         Appcelerator Titanium - Flexibility vs. Performance
Titanium 2.0
    • Improved stability
    • Improved platform parity
    • Improved performance
    • Appcelerator Cloud Services




5             Appcelerator Titanium - Flexibility vs. Performance
Some Mobile Dev Tools
             Mobile Web                                          Flexibility → ∞
                                                                 + High Level Language
                                                                 + High Level APIs
                                                                 + Dynamic updates
                                                                 + Cross Platform


                                    Titanium
             PhoneGap
                                     Mobile



                                                   RubyMotion



    0 ← Performance                                                  1
    + Execution Speed
    + Native UX
    + Native capabilities

6              Appcelerator Titanium - Flexibility vs. Performance
Some Mobile Dev Tools
             Mobile Web                                          Flexibility → ∞
                                                                 + High Level Language
                                                                 + High Level APIs
                                                                 + Dynamic updates
                                                                 + Cross Platform


                                    Titanium         ?
             PhoneGap
                                     Mobile



                                     ?             RubyMotion



    0 ← Performance                                                  1
    + Execution Speed
    + Native UX
    + Native capabilities

6              Appcelerator Titanium - Flexibility vs. Performance
An example: Ti.UI.TableView




7      Appcelerator Titanium - Flexibility vs. Performance
Common Problems
    • Slow transitions
      – the table view takes ages to show up
    • Choppy scrolling
      – Everybody wants super-slick animations, isn’t it?




8             Appcelerator Titanium - Flexibility vs. Performance
Towards Increased Performance
    • Understand the tools, then:


                                    Measure



                  Optimize

                                           Learn



9             Appcelerator Titanium - Flexibility vs. Performance
Runtime Environment
                                 JS APP                                           JS APP

                                                            V8
                        Parser                                           Parser
     JavaScriptCore




                      Bytecode             Titanium                     Native             Titanium
                        gen                Modules                     Code Gen            Modules
                                                             OPT
                                                                         Native
                      Interpreter
                                                                         Code


                             IOS SDK                                      ANDROID SDK




10                                  Appcelerator Titanium - Flexibility vs. Performance
Runtime Environment
                                    JS APP                                          JS APP

                                                              V8
                           Parser                                          Parser
     JavaScriptCore




                         Bytecode            Titanium                     Native             Titanium
                           gen               Modules                     Code Gen            Modules
                                                               OPT
                          JIT
                      NOInterpreter                                        Native
                                                                           Code


                                IOS SDK                                     ANDROID SDK




10                                    Appcelerator Titanium - Flexibility vs. Performance
Runtime Environment
                                    JS APP                                          JS APP

                                                              V8
                           Parser                                          Parser
     JavaScriptCore




                         Bytecode            Titanium                     Native             Titanium
                           gen               Modules                     Code Gen            Modules
                                                               OPT
                          JIT
                      NOInterpreter                                        Native
                                                                           Code


                                IOS SDK                                     ANDROID SDK




10                                    Appcelerator Titanium - Flexibility vs. Performance
Runtime Environment
                                    JS APP                                          JS APP

                                                              V8
                           Parser                                          Parser
     JavaScriptCore




                         Bytecode            Titanium                     Native             Titanium
                           gen               Modules                     Code Gen            Modules
                                                               OPT
                          JIT
                      NOInterpreter                                        Native
                                                                           Code


                                IOS SDK                                     ANDROID SDK




10                                    Appcelerator Titanium - Flexibility vs. Performance
Measure: which runs faster?
     function processRow(row) {
         return {title: row.info};
     }


                                            1                                            2
     var rows = [];                                 var rows = [];
     for (var r = 0; r < array.length; r++) {       for (var r = 0; r < array.length; r++) {
       rows.push({title: array[r].info});             rows.push(processRow(array[r]));
     }                                              }




                                            3                                            4
     var len = array.length;                        var len = array.length;
     var rows = [];                                 var rows = [];
     for (var r = 0; r < len; r++) {                for (var r = 0; r < len; r++) {
       rows.push({title: array[r].info});             rows.push(processRow(array[r]));
     }                                              }



                                                                   5
                               var rows = array.map(processRow);



11                    Appcelerator Titanium - Flexibility vs. Performance
Tests on iPhone 4
          1000




           100
     ms




            10




             1
                        100               1000              10000

                                   Number of Rows

            1) for + inline                 2) for + funct
            3) for + inline + cache len     4) for + funct + cache len
            5) map


12        Appcelerator Titanium - Flexibility vs. Performance
Which runs faster?
     function processRow2(row) {
         return Ti.UI.createTableViewRow({title: row.info});
     }


                                             1                                            2
     var rows = [];                                 var rows = [];
     for (var r = 0; r < array.length; r++) {       for (var r = 0; r < array.length; r++) {
       rows.push(Ti.UI.createTableViewRow(            rows.push(processRow2(array[r]));
         {title: array[r].info}));                  }
     }


                                             3                                            4
     var len = array.length;                        var len = array.length;
     var rows = [];                                 var rows = [];
     for (var r = 0; r < len; r++) {                for (var r = 0; r < len; r++) {
       rows.push(Ti.UI.createTableViewRow(            rows.push(processRow2(array[r]));
         {title: array[r].info}));                  }
     }


                                                                   5
                              var rows = array.map(processRow2);


13                    Appcelerator Titanium - Flexibility vs. Performance
Tests on iPhone 4
          10000



          1000
     ms




            100



             10



              1
                         10                 100               1000
                                Number of rows

              1) for + inline                 2) for + funct
              3) for + inline + cache len     4) for + funct + cache len
              5) map


14        Appcelerator Titanium - Flexibility vs. Performance
Tests on iPhone 4
          10000


                                                            ES E
                       TH
          1000

                     T
                    S !!
                   U !
                  R TS
                 T L
     ms




               ’T U
            100




              N ES
             O R
            D
             10



              1
                         10                 100               1000
                                Number of rows

              1) for + inline                 2) for + funct
              3) for + inline + cache len     4) for + funct + cache len
              5) map


14        Appcelerator Titanium - Flexibility vs. Performance
WHY?
     • They’re not generalizable
     • Your code won’t look like the one presented here
     • Do your own measurements




15             Appcelerator Titanium - Flexibility vs. Performance
Is table creation slow?
     • Obtaining some rough figures:


       var start = new Date().getTime();

       //your code goes here

       var end = new Date().getTime();
       Ti.API.info('elapsed ms: ' + (end - start));




16            Appcelerator Titanium - Flexibility vs. Performance
Are there more accurate tools?
     • mmm.... AFAIK NO!




17            Appcelerator Titanium - Flexibility vs. Performance
Android DDMS + Traceview




18     Appcelerator Titanium - Flexibility vs. Performance
Android DDMS + Traceview




     WHERE’S MY JS???
18     Appcelerator Titanium - Flexibility vs. Performance
Xcode Instruments: profiler tool




19        Appcelerator Titanium - Flexibility vs. Performance
Xcode Instruments: profiler tool



                                                   JS code hidden here




19        Appcelerator Titanium - Flexibility vs. Performance
Titanium Profiler... still to come




20        Appcelerator Titanium - Flexibility vs. Performance
Titanium Profiler (iOS only)
     • Custom version of the Ti JavaScriptCore library
     • Work in progress
     • Some info here
          http://titaniumninja.com/profiling-ti-mobile-apps-is-it-possible/
     • Will be possibly integrated in Ti Mobile
     • Stay tuned on
          http://titaniumninja.com/




21                Appcelerator Titanium - Flexibility vs. Performance
Is table creation REALLY slow?
     • Try optimizing the row creation loop body
     • Implement Lazy loading
       – Initialize the table with fewer rows and show it
         immediately
       – Meantime continue creating the remaining rows and
         update the table with the complete row set




22             Appcelerator Titanium - Flexibility vs. Performance
Wanna smooth scrolling?




23    Appcelerator Titanium - Flexibility vs. Performance
Instruments: Core Animation




24      Appcelerator Titanium - Flexibility vs. Performance
Tables with complex rows are slow




                                ~35-40 FPS
                                   Expected: ~60 FPS



25         Appcelerator Titanium - Flexibility vs. Performance
1. Blended layers




 These labels are transparent, even if we set
 the background color, or a background image



26                 Appcelerator Titanium - Flexibility vs. Performance
What can we do?

                -(UILabel*)label
                {
                ! if (label==nil)
                ! {
                        label = [[UILabel alloc] initWithFrame:CGRectZero];
                        label.backgroundColor = [UIColor whiteColor];
                        label.numberOfLines = 0;
                        [self addSubview:label];
                        label.opaque = YES;
                        self.opaque = YES;
                        self.backgroundColor = [UIColor whiteColor];
                ! }
                ! return label;
                }                                               TiUILabel.m:104


     Discussion (Cfr. UIView Reference)
     “The opaque property provides a hint to the drawing system as to how it should treat the view. If set
     to YES, the drawing system treats the view as fully opaque, which allows the drawing system to
     optimize some drawing operations and improve performance”



27                     Appcelerator Titanium - Flexibility vs. Performance
What can we do?


                                                            !!
                -(UILabel*)label
                {


                                                           !
                ! if (label==nil)



                                                        IX
                ! {



                                                       F
                        label = [[UILabel alloc] initWithFrame:CGRectZero];



                                                     A
                        label.backgroundColor = [UIColor whiteColor];
                        label.numberOfLines = 0;


                                         T
                        [self addSubview:label];


                                       O
                        label.opaque = YES;


                                      N
                        self.opaque = YES;
                        self.backgroundColor = [UIColor whiteColor];
                ! }
                ! return label;
                }                                               TiUILabel.m:104


     Discussion (Cfr. UIView Reference)
     “The opaque property provides a hint to the drawing system as to how it should treat the view. If set
     to YES, the drawing system treats the view as fully opaque, which allows the drawing system to
     optimize some drawing operations and improve performance”



27                     Appcelerator Titanium - Flexibility vs. Performance
Result




                   ~45-50 FPS




28   Appcelerator Titanium - Flexibility vs. Performance
2. Offscreen rendered layers




29      Appcelerator Titanium - Flexibility vs. Performance
Solution
     • Don’t use rounded corners (borderRadius)
     • Use an image mask instead


                               var img = Ti.UI.createMaskedImage({
                                   mask : 'mask.png',// alpha mask
                                   image : myPicture,//image to mask
                                   mode : Ti.UI.iOS.BLEND_MODE_SCREEN
                               });




30            Appcelerator Titanium - Flexibility vs. Performance
What about FPSs?




                   ~55-60 FPS
               (Just using image masks)




31   Appcelerator Titanium - Flexibility vs. Performance
Not satisfied? Going fully native
     • Let’s create a custom optimized UITableView
     • We’ll expose it through a native module




32             Appcelerator Titanium - Flexibility vs. Performance
API for the custom view
     • API
         •   createMessagesView(properties);
         •   setMessages([]messages);
         •   insert(message);
         •   addEventListener(‘click’, callback);
     • Config
                    {
                        rowBackgroundColor: '#efefef',
                        nameColorIfMe: '#191919',
                        nameColorIfOther: '#8f032c',
                        …
                    }




33              Appcelerator Titanium - Flexibility vs. Performance
API for the custom view
     • API
                                          IT Y
          • setMessages([]messages);IB
                                       IL
          • createMessagesView(properties);

          • insert(message);     EX
                              FL callback);
                          ED
          • addEventListener(‘click’,
                        S
     • Config
                   R EA
                EC
                  {



              D
                      rowBackgroundColor: '#efefef',
                      nameColorIfMe: '#191919',
                      nameColorIfOther: '#8f032c',
                      …
                  }




33            Appcelerator Titanium - Flexibility vs. Performance
Message model

     {
          isMe: true,
          name: "Vincent",
          picture: "vin.png",
          body: "It's not. It's the same ballpark.",
          date: 12394838299 //unix timestamp
     },




34             Appcelerator Titanium - Flexibility vs. Performance
A single row

                          name                 date


     picture
                                                            Click

                              body




35         Appcelerator Titanium - Flexibility vs. Performance
Traditional UITableViewCell
     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
     *)indexPath
     {!      !
         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageCell"];
     !
         if (cell == nil) {
             cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                    reuseIdentifier:@"MessageCell"] autorelease];

             UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(75.0, 25.0, 120.0, 18.0)];
             nameLabel.font = [UIFont boldSystemFontOfSize:16.0];
             nameLabel.textAlignment = UITextAlignmentLeft;
     !   !     nameLabel.backgroundColor = rowBackgroundColor;
     !   !
             [cell.contentView addSubview:nameLabel];

         } else {
             //...
         }

         Message *msg = [messages objectAtIndex:(indexPath.row)];
         BOOL isMe = [TiUtils boolValue:[dict objectForKey:@"isMe"]];
         nameLabel.textColor = isMe ? nameColorIfMe : nameColorIfOther;
         //...




36                      Appcelerator Titanium - Flexibility vs. Performance
Not fast enough? Use FastCells
     - (void) drawContentView:(CGRect)rect {               Low level drawing primitives
         if (message == nil)
             return;

         CGContextRef context = UIGraphicsGetCurrentContext();

         CGContextClearRect(context, rect);

         CGFloat max_width = self.contentView.frame.size.width;


         if (message.isMe)
              [nameColorIfMe set];
         else
              [nameColorIfOther set];

         [message.name drawInRect:CGRectMake(userInfoLeft, userInfoTop, rectWidth(userInfoLeft,
          userInfoRight, max_width), userInfoHeight) withFont:bigBoldFont
          lineBreakMode:UILineBreakModeTailTruncation];

          //...
     }




37                     Appcelerator Titanium - Flexibility vs. Performance
Concluding remarks on Titanium
     • Is it worth it?
     • Does it really speeds up development?
     • Is developing with Titanium “better” or “worse”
       than making parallel per-platform developments?




38            Appcelerator Titanium - Flexibility vs. Performance
Where’s the value?
     • Quick prototyping iterations
     • Single complex business-logic core
     • Cross platform deployment
     • Maintainability of the project in the long term




39             Appcelerator Titanium - Flexibility vs. Performance
Some interesting reads
     •   JavaScriptCore, the WebKit JS implementation - http://wingolog.org/archives/
         2011/10/28/javascriptcore-the-webkit-js-implementation
     •   v8: a tale of two compilers - http://wingolog.org/archives/2011/07/05/v8-a-tale-
         of-two-compilers
     •   JSC v/s V8 performance on ARM - http://xc0ffee.wordpress.com/2011/09/07/
         webkit-gtk-jsc-vs-v8-performance-on-arm/
     •   The Future of JavaScript Engines: Replace Them With JavaScript Compilers -
         http://shorestreet.com/node/43
     •   Optimisation: don't waste your time - http://www.scirra.com/blog/83/
         optimisation-dont-waste-your-time
     •   Guidelines for JavaScript Programs: Are They Still Necessary? - http://www.inf.u-
         szeged.hu/~akiss/pub/pdf/herczeg_guidelines.pdf




40                    Appcelerator Titanium - Flexibility vs. Performance
Thank YOU!




                           Any question?

41   Appcelerator Titanium - Flexibility vs. Performance

More Related Content

PDF
Extending Titanium with native iOS and Android modules
PPT
Extending Appcelerator Titanium Mobile through Native Modules
PPTX
Introduction to Module Development with Appcelerator Titanium
PDF
Developing and-benchmarking-native-linux-applications-on-android
PDF
Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012
PPTX
Beyond Continuous Delivery at DevOpsDays Rome 2012
PDF
A Review Paper on Kotlin Programming Language
PDF
Framework Engineering
Extending Titanium with native iOS and Android modules
Extending Appcelerator Titanium Mobile through Native Modules
Introduction to Module Development with Appcelerator Titanium
Developing and-benchmarking-native-linux-applications-on-android
Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012
Beyond Continuous Delivery at DevOpsDays Rome 2012
A Review Paper on Kotlin Programming Language
Framework Engineering

What's hot (20)

PDF
International Journal of Engineering Research and Development
PPT
SynapseIndia mobile apps deployment framework architecture
PDF
Forum Nokia Dev. Camp - WRT training Paris_17&18 Nov.
PDF
Dominik Gusenbauer Qt Mobility
PDF
Wc Mand Connectors2
 
PDF
The Forces Driving Java
KEY
Scala on androids
PPTX
Useful C++ Features You Should be Using
PPT
Profiler Instrumentation Using Metaprogramming Techniques
PPTX
2018 20 best id es for python programming
PDF
Zend Framework Getting Started For I5
PDF
Enforce reproducibility: dependency management and build automation
DOCX
SachinBC_Resume
PPT
Java for Recruiters
PDF
Testing on Android
PPTX
Programming in HTML5 With Java Script and CSS3
PDF
Android on Windows 11 - A Developer's Perspective (Windows Subsystem For Andr...
PDF
Qt - for stack overflow developer conference
PPSX
CR Bridge Solutions Pvt Ltd. Java slides
PPTX
Getting started with the NDK
International Journal of Engineering Research and Development
SynapseIndia mobile apps deployment framework architecture
Forum Nokia Dev. Camp - WRT training Paris_17&18 Nov.
Dominik Gusenbauer Qt Mobility
Wc Mand Connectors2
 
The Forces Driving Java
Scala on androids
Useful C++ Features You Should be Using
Profiler Instrumentation Using Metaprogramming Techniques
2018 20 best id es for python programming
Zend Framework Getting Started For I5
Enforce reproducibility: dependency management and build automation
SachinBC_Resume
Java for Recruiters
Testing on Android
Programming in HTML5 With Java Script and CSS3
Android on Windows 11 - A Developer's Perspective (Windows Subsystem For Andr...
Qt - for stack overflow developer conference
CR Bridge Solutions Pvt Ltd. Java slides
Getting started with the NDK
Ad

Similar to Titanium Mobile: flexibility vs. performance (20)

PPTX
Keynote: Techday7 appcelerator titanium
PPTX
Android and Intel Inside
PDF
Octopod Mobile Development Platform for rapid cross-platform Enterprise IT Mo...
PDF
A Graphical Language for Real-Time Critical Robot Commands
KEY
Mobile Drupal
PDF
[2011-17-C-4] Heroku & database.com
PDF
What is Google App Engine?
PPTX
Cross Platform Mobile Apps with APIs from Qcon San Francisco
KEY
SumitK's mobile app dev using drupal as base ststem
PDF
App Engine overview (Android meetup 06-10)
PPTX
Continuous delivery on the cloud
PDF
Developing on StackMob - Flying Monkey Interactive Evaluates BaaS
PDF
Python vs. Node.js: Which is Best for your Web Application?
PPTX
Eco system apps
PPTX
Building single page applications
PPTX
OSCON 2012: Design and Debug HTML5 Apps for Devices with RIB and Web Simulator
PPTX
tittanium
PDF
Alfresco Day Madrid - Jeff Potts - Activiti
PDF
Alfresco day madrid jeff potts - activiti
PPT
Appcelerator Titanium App Development
Keynote: Techday7 appcelerator titanium
Android and Intel Inside
Octopod Mobile Development Platform for rapid cross-platform Enterprise IT Mo...
A Graphical Language for Real-Time Critical Robot Commands
Mobile Drupal
[2011-17-C-4] Heroku & database.com
What is Google App Engine?
Cross Platform Mobile Apps with APIs from Qcon San Francisco
SumitK's mobile app dev using drupal as base ststem
App Engine overview (Android meetup 06-10)
Continuous delivery on the cloud
Developing on StackMob - Flying Monkey Interactive Evaluates BaaS
Python vs. Node.js: Which is Best for your Web Application?
Eco system apps
Building single page applications
OSCON 2012: Design and Debug HTML5 Apps for Devices with RIB and Web Simulator
tittanium
Alfresco Day Madrid - Jeff Potts - Activiti
Alfresco day madrid jeff potts - activiti
Appcelerator Titanium App Development
Ad

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPT
Teaching material agriculture food technology
PDF
Electronic commerce courselecture one. Pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Encapsulation theory and applications.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
KodekX | Application Modernization Development
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
The AUB Centre for AI in Media Proposal.docx
Digital-Transformation-Roadmap-for-Companies.pptx
Programs and apps: productivity, graphics, security and other tools
Per capita expenditure prediction using model stacking based on satellite ima...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
20250228 LYD VKU AI Blended-Learning.pptx
Teaching material agriculture food technology
Electronic commerce courselecture one. Pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Spectroscopy.pptx food analysis technology
Big Data Technologies - Introduction.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
MYSQL Presentation for SQL database connectivity
Chapter 3 Spatial Domain Image Processing.pdf
Encapsulation theory and applications.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
KodekX | Application Modernization Development
Advanced methodologies resolving dimensionality complications for autism neur...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton

Titanium Mobile: flexibility vs. performance

  • 1. Appcelerator Titanium Mobile FLEXIBILITY VS PERFORMANCE Olivier Morandi
  • 2. $ whoami Olivier Morandi Software engineer http://titaniumninja.com olivier.morandi@gmail.com @olivier_morandi https://github.com/omorandi 2 Appcelerator Titanium - Flexibility vs. Performance
  • 3. Titanium Mobile • Rapid development & prototyping tool • Single high level language: JS • Multiple deployment platforms (iOS, Android, ...) • We can leverage an ever growing set of JS libraries and modules (web, node.js, etc.) • Possibility to extend the framework with native modules 3 Appcelerator Titanium - Flexibility vs. Performance
  • 4. Titanium Apps are NATIVE Can we also expect a native User Experience? 4 Appcelerator Titanium - Flexibility vs. Performance
  • 5. Titanium 2.0 • Improved stability • Improved platform parity • Improved performance • Appcelerator Cloud Services 5 Appcelerator Titanium - Flexibility vs. Performance
  • 6. Some Mobile Dev Tools Mobile Web Flexibility → ∞ + High Level Language + High Level APIs + Dynamic updates + Cross Platform Titanium PhoneGap Mobile RubyMotion 0 ← Performance 1 + Execution Speed + Native UX + Native capabilities 6 Appcelerator Titanium - Flexibility vs. Performance
  • 7. Some Mobile Dev Tools Mobile Web Flexibility → ∞ + High Level Language + High Level APIs + Dynamic updates + Cross Platform Titanium ? PhoneGap Mobile ? RubyMotion 0 ← Performance 1 + Execution Speed + Native UX + Native capabilities 6 Appcelerator Titanium - Flexibility vs. Performance
  • 8. An example: Ti.UI.TableView 7 Appcelerator Titanium - Flexibility vs. Performance
  • 9. Common Problems • Slow transitions – the table view takes ages to show up • Choppy scrolling – Everybody wants super-slick animations, isn’t it? 8 Appcelerator Titanium - Flexibility vs. Performance
  • 10. Towards Increased Performance • Understand the tools, then: Measure Optimize Learn 9 Appcelerator Titanium - Flexibility vs. Performance
  • 11. Runtime Environment JS APP JS APP V8 Parser Parser JavaScriptCore Bytecode Titanium Native Titanium gen Modules Code Gen Modules OPT Native Interpreter Code IOS SDK ANDROID SDK 10 Appcelerator Titanium - Flexibility vs. Performance
  • 12. Runtime Environment JS APP JS APP V8 Parser Parser JavaScriptCore Bytecode Titanium Native Titanium gen Modules Code Gen Modules OPT JIT NOInterpreter Native Code IOS SDK ANDROID SDK 10 Appcelerator Titanium - Flexibility vs. Performance
  • 13. Runtime Environment JS APP JS APP V8 Parser Parser JavaScriptCore Bytecode Titanium Native Titanium gen Modules Code Gen Modules OPT JIT NOInterpreter Native Code IOS SDK ANDROID SDK 10 Appcelerator Titanium - Flexibility vs. Performance
  • 14. Runtime Environment JS APP JS APP V8 Parser Parser JavaScriptCore Bytecode Titanium Native Titanium gen Modules Code Gen Modules OPT JIT NOInterpreter Native Code IOS SDK ANDROID SDK 10 Appcelerator Titanium - Flexibility vs. Performance
  • 15. Measure: which runs faster? function processRow(row) { return {title: row.info}; } 1 2 var rows = []; var rows = []; for (var r = 0; r < array.length; r++) { for (var r = 0; r < array.length; r++) { rows.push({title: array[r].info}); rows.push(processRow(array[r])); } } 3 4 var len = array.length; var len = array.length; var rows = []; var rows = []; for (var r = 0; r < len; r++) { for (var r = 0; r < len; r++) { rows.push({title: array[r].info}); rows.push(processRow(array[r])); } } 5 var rows = array.map(processRow); 11 Appcelerator Titanium - Flexibility vs. Performance
  • 16. Tests on iPhone 4 1000 100 ms 10 1 100 1000 10000 Number of Rows 1) for + inline 2) for + funct 3) for + inline + cache len 4) for + funct + cache len 5) map 12 Appcelerator Titanium - Flexibility vs. Performance
  • 17. Which runs faster? function processRow2(row) { return Ti.UI.createTableViewRow({title: row.info}); } 1 2 var rows = []; var rows = []; for (var r = 0; r < array.length; r++) { for (var r = 0; r < array.length; r++) { rows.push(Ti.UI.createTableViewRow( rows.push(processRow2(array[r])); {title: array[r].info})); } } 3 4 var len = array.length; var len = array.length; var rows = []; var rows = []; for (var r = 0; r < len; r++) { for (var r = 0; r < len; r++) { rows.push(Ti.UI.createTableViewRow( rows.push(processRow2(array[r])); {title: array[r].info})); } } 5 var rows = array.map(processRow2); 13 Appcelerator Titanium - Flexibility vs. Performance
  • 18. Tests on iPhone 4 10000 1000 ms 100 10 1 10 100 1000 Number of rows 1) for + inline 2) for + funct 3) for + inline + cache len 4) for + funct + cache len 5) map 14 Appcelerator Titanium - Flexibility vs. Performance
  • 19. Tests on iPhone 4 10000 ES E TH 1000 T S !! U ! R TS T L ms ’T U 100 N ES O R D 10 1 10 100 1000 Number of rows 1) for + inline 2) for + funct 3) for + inline + cache len 4) for + funct + cache len 5) map 14 Appcelerator Titanium - Flexibility vs. Performance
  • 20. WHY? • They’re not generalizable • Your code won’t look like the one presented here • Do your own measurements 15 Appcelerator Titanium - Flexibility vs. Performance
  • 21. Is table creation slow? • Obtaining some rough figures: var start = new Date().getTime(); //your code goes here var end = new Date().getTime(); Ti.API.info('elapsed ms: ' + (end - start)); 16 Appcelerator Titanium - Flexibility vs. Performance
  • 22. Are there more accurate tools? • mmm.... AFAIK NO! 17 Appcelerator Titanium - Flexibility vs. Performance
  • 23. Android DDMS + Traceview 18 Appcelerator Titanium - Flexibility vs. Performance
  • 24. Android DDMS + Traceview WHERE’S MY JS??? 18 Appcelerator Titanium - Flexibility vs. Performance
  • 25. Xcode Instruments: profiler tool 19 Appcelerator Titanium - Flexibility vs. Performance
  • 26. Xcode Instruments: profiler tool JS code hidden here 19 Appcelerator Titanium - Flexibility vs. Performance
  • 27. Titanium Profiler... still to come 20 Appcelerator Titanium - Flexibility vs. Performance
  • 28. Titanium Profiler (iOS only) • Custom version of the Ti JavaScriptCore library • Work in progress • Some info here http://titaniumninja.com/profiling-ti-mobile-apps-is-it-possible/ • Will be possibly integrated in Ti Mobile • Stay tuned on http://titaniumninja.com/ 21 Appcelerator Titanium - Flexibility vs. Performance
  • 29. Is table creation REALLY slow? • Try optimizing the row creation loop body • Implement Lazy loading – Initialize the table with fewer rows and show it immediately – Meantime continue creating the remaining rows and update the table with the complete row set 22 Appcelerator Titanium - Flexibility vs. Performance
  • 30. Wanna smooth scrolling? 23 Appcelerator Titanium - Flexibility vs. Performance
  • 31. Instruments: Core Animation 24 Appcelerator Titanium - Flexibility vs. Performance
  • 32. Tables with complex rows are slow ~35-40 FPS Expected: ~60 FPS 25 Appcelerator Titanium - Flexibility vs. Performance
  • 33. 1. Blended layers These labels are transparent, even if we set the background color, or a background image 26 Appcelerator Titanium - Flexibility vs. Performance
  • 34. What can we do? -(UILabel*)label { ! if (label==nil) ! { label = [[UILabel alloc] initWithFrame:CGRectZero]; label.backgroundColor = [UIColor whiteColor]; label.numberOfLines = 0; [self addSubview:label]; label.opaque = YES; self.opaque = YES; self.backgroundColor = [UIColor whiteColor]; ! } ! return label; } TiUILabel.m:104 Discussion (Cfr. UIView Reference) “The opaque property provides a hint to the drawing system as to how it should treat the view. If set to YES, the drawing system treats the view as fully opaque, which allows the drawing system to optimize some drawing operations and improve performance” 27 Appcelerator Titanium - Flexibility vs. Performance
  • 35. What can we do? !! -(UILabel*)label { ! ! if (label==nil) IX ! { F label = [[UILabel alloc] initWithFrame:CGRectZero]; A label.backgroundColor = [UIColor whiteColor]; label.numberOfLines = 0; T [self addSubview:label]; O label.opaque = YES; N self.opaque = YES; self.backgroundColor = [UIColor whiteColor]; ! } ! return label; } TiUILabel.m:104 Discussion (Cfr. UIView Reference) “The opaque property provides a hint to the drawing system as to how it should treat the view. If set to YES, the drawing system treats the view as fully opaque, which allows the drawing system to optimize some drawing operations and improve performance” 27 Appcelerator Titanium - Flexibility vs. Performance
  • 36. Result ~45-50 FPS 28 Appcelerator Titanium - Flexibility vs. Performance
  • 37. 2. Offscreen rendered layers 29 Appcelerator Titanium - Flexibility vs. Performance
  • 38. Solution • Don’t use rounded corners (borderRadius) • Use an image mask instead var img = Ti.UI.createMaskedImage({ mask : 'mask.png',// alpha mask image : myPicture,//image to mask mode : Ti.UI.iOS.BLEND_MODE_SCREEN }); 30 Appcelerator Titanium - Flexibility vs. Performance
  • 39. What about FPSs? ~55-60 FPS (Just using image masks) 31 Appcelerator Titanium - Flexibility vs. Performance
  • 40. Not satisfied? Going fully native • Let’s create a custom optimized UITableView • We’ll expose it through a native module 32 Appcelerator Titanium - Flexibility vs. Performance
  • 41. API for the custom view • API • createMessagesView(properties); • setMessages([]messages); • insert(message); • addEventListener(‘click’, callback); • Config { rowBackgroundColor: '#efefef', nameColorIfMe: '#191919', nameColorIfOther: '#8f032c', … } 33 Appcelerator Titanium - Flexibility vs. Performance
  • 42. API for the custom view • API IT Y • setMessages([]messages);IB IL • createMessagesView(properties); • insert(message); EX FL callback); ED • addEventListener(‘click’, S • Config R EA EC { D rowBackgroundColor: '#efefef', nameColorIfMe: '#191919', nameColorIfOther: '#8f032c', … } 33 Appcelerator Titanium - Flexibility vs. Performance
  • 43. Message model { isMe: true, name: "Vincent", picture: "vin.png", body: "It's not. It's the same ballpark.", date: 12394838299 //unix timestamp }, 34 Appcelerator Titanium - Flexibility vs. Performance
  • 44. A single row name date picture Click body 35 Appcelerator Titanium - Flexibility vs. Performance
  • 45. Traditional UITableViewCell - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {! ! UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageCell"]; ! if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MessageCell"] autorelease]; UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(75.0, 25.0, 120.0, 18.0)]; nameLabel.font = [UIFont boldSystemFontOfSize:16.0]; nameLabel.textAlignment = UITextAlignmentLeft; ! ! nameLabel.backgroundColor = rowBackgroundColor; ! ! [cell.contentView addSubview:nameLabel]; } else { //... } Message *msg = [messages objectAtIndex:(indexPath.row)]; BOOL isMe = [TiUtils boolValue:[dict objectForKey:@"isMe"]]; nameLabel.textColor = isMe ? nameColorIfMe : nameColorIfOther; //... 36 Appcelerator Titanium - Flexibility vs. Performance
  • 46. Not fast enough? Use FastCells - (void) drawContentView:(CGRect)rect { Low level drawing primitives if (message == nil) return; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextClearRect(context, rect); CGFloat max_width = self.contentView.frame.size.width; if (message.isMe) [nameColorIfMe set]; else [nameColorIfOther set]; [message.name drawInRect:CGRectMake(userInfoLeft, userInfoTop, rectWidth(userInfoLeft, userInfoRight, max_width), userInfoHeight) withFont:bigBoldFont lineBreakMode:UILineBreakModeTailTruncation]; //... } 37 Appcelerator Titanium - Flexibility vs. Performance
  • 47. Concluding remarks on Titanium • Is it worth it? • Does it really speeds up development? • Is developing with Titanium “better” or “worse” than making parallel per-platform developments? 38 Appcelerator Titanium - Flexibility vs. Performance
  • 48. Where’s the value? • Quick prototyping iterations • Single complex business-logic core • Cross platform deployment • Maintainability of the project in the long term 39 Appcelerator Titanium - Flexibility vs. Performance
  • 49. Some interesting reads • JavaScriptCore, the WebKit JS implementation - http://wingolog.org/archives/ 2011/10/28/javascriptcore-the-webkit-js-implementation • v8: a tale of two compilers - http://wingolog.org/archives/2011/07/05/v8-a-tale- of-two-compilers • JSC v/s V8 performance on ARM - http://xc0ffee.wordpress.com/2011/09/07/ webkit-gtk-jsc-vs-v8-performance-on-arm/ • The Future of JavaScript Engines: Replace Them With JavaScript Compilers - http://shorestreet.com/node/43 • Optimisation: don't waste your time - http://www.scirra.com/blog/83/ optimisation-dont-waste-your-time • Guidelines for JavaScript Programs: Are They Still Necessary? - http://www.inf.u- szeged.hu/~akiss/pub/pdf/herczeg_guidelines.pdf 40 Appcelerator Titanium - Flexibility vs. Performance
  • 50. Thank YOU! Any question? 41 Appcelerator Titanium - Flexibility vs. Performance