SlideShare a Scribd company logo
1 of 38
Download to read offline
Series 40 Developer Training     Michael Samarin
                                 Paul Houghton
                                 Timo Saarinen
Designing and coding Series 40
Java apps for high performance   Futurice Ltd
Today’s Topics
» Performance Basics on Series 40
» Mobile Front End Architecture Patterns
» Choosing GUI, Caching, Threading
» Low Level “Micro” Performance Optimization
Miller, R. B. (1968)
Response time in man-computer conversational
transactions.
Proc. AFIPS Fall Joint Computer ConferenceVol. 33, 267-277


» 0.1 second is about the limit for having the
  user feel that the system is reacting
  instantaneously, meaning that no special
  feedback is necessary except to display the
  result.
» 1.0 second is about the limit for the user's flow of
  thought to stay uninterrupted, even though the user will
  notice the delay. Normally, no special feedback is
  necessary during delays of more than 0.1 but less than
  1.0 second, but the user does lose the feeling of
  operating directly on the data.

» 10 seconds is about the limit for keeping the user's
  attention focused on the dialogue. For longer delays,
  users will want to perform other tasks while waiting for
  the computer to finish, so they should be given feedback
  indicating when the computer expects to be done.
  Feedback during the delay is especially important if the
  response time is likely to be highly variable, since users
  will then not know what to expect.
Choosing GUI Strategy
» LCDUI Forms.
» Canvas
» GameCanvas
» LWUIT
LCDUI Forms
» Fast, simple and standard way of making UI.
» On full touch Asha very attractive looking and have
  huge UX improvements.
» Not as fast as Canvas. Animation on a Form is much
  slower than on a Canvas, and there is no way to
  influence the vertical scroll position, animate transitions
  between screen, or shift to a full screen view. You can,
  however, slightly increase the performance when
  changing screens by using just one Form and re-
  populating it with new Items.
» http://www.developer.nokia.com/Resources/Library/Full_Touch
Canvas
» Highly customizable way of making UI.
» You have to take care of render timing yourself, or you can use
  Nokia’s FrameAnimator class to quickly create effects such as
  kinetic scrolling.
» Any part of your code can call Canvas.repaint() to signal that
  painting should occur soon.
» The most important performance tip for navigating through a
  Canvas-based UI is to implement your own View class to
  represent each screen, and paint all Views on one Canvas rather
  than switching from one Canvas to another, which can be slow
  and does not give you the possibility of animating the transition
  for smooth effect.
GameCanvas
» GameCanvas is double buffered with more control over the
  painting cycle and threading.
» Unlike Canvas, you should create your own Thread, which calls
  GameCanvas.paint() directly to fill the graphics buffer, and then
  GameCanvas.flushGraphics() to instantly blit the graphics buffer
  onto the screen.
LWUIT
» LWUIT (Lightweight User Interface Toolkit) is a toolkit for
  creating SWING-like applications without some of the complexity
  of SWING.
» Like Form, it offers basic components, but it adds to this better
  layouts, styles and theming, bundling own fonts into your
  application, and animated screen transitions.
» LWUIT is implemented on top of a Canvas, but it is a large and
  complex library written to be a general purpose replacement for
  the default UI on many different phones.
» LWUIT and the associated themes and any fonts you include
  quickly make your JAR file grow quite large.
» http://projects.developer.nokia.com/LWUIT_for_Series_40
Heap Memory
» On Series 40 only from 2 to 4 MB.
» Instances of classes (objects) and primitive types
  are created in the heap.
» Total number of methods in classes loaded by JVM
  has a direct impact on how much heap space is left
  for other data. These memory allocations are
  permanent for the runtime of the application and
  are not dynamically unloaded by the JVM once a
  class is no longer in use.
Recursive Algorithms and Stack Memory
» Variables passed as arguments to a method are passed on
  the current thread’s stack. Method variables of primitive
  types are also allocated on the stack.
» Recursive algorithms are algorithms where a method calls
  itself in a loop to complete a task. As a result, they create
  multiple stack frames.
   ›   They use a lot of stack memory. The same method is called repeatedly, and only as the
       application completes does it unwind the queued stack frames. This extra stack
       memory is often not useful, and stack memory per thread is limited and such heavy
       stack use may well cause an OutOfMemoryException well before you are actually out of
       heap memory.

   ›   Recursive algorithms can be slow. Each method call includes a certain amount of
       overhead, which is not really necessary since a recursive algorithm can be unwound into
       a non-recursive equivalent loop that does not include the relatively heavy method call.
› Provides basic “free”
                 optimization
               › Fixes code redundancy and
                 pre-calculate things
Compile Time     whenever possible
Optimization   › Minimizes memory usage
         and   › Should be last step in
 Obfuscation     building apps – takes time
                 and makes debugging
                 difficult
               › Doesn’t fix wrong
                 architecture
Compile Time Optimization
Proguard Bytecode Obfuscator
Obfuscation Example: Battle Tank
https://projects.developer.nokia.com/JMEBattleTank




                              › JAR File size decreased by 4%
                                (889 -> 852 kB)
                              › RAM usage decreased by 14%
                                (161 -> 138 kB)
Architecture changes
» Carefully consider architecture of your drawing loop and
  input loops and decouple them whenever possible.
» Example: panorama drawing and sensor driving loop.
» Original example:
» http://www.youtube.com/watch?v=PfW4BVHgri8
» After optimization:
» http://www.youtube.com/watch?v=xSRYVYrNNMI
WeakReference object Caching
» Best pattern for using all available heap memory, but
  never running into the dreaded OutOfMemoryError.
» CLDC 1.1 WeakReference
» When an object is referenced by a WeakReference, and not
  using traditional Object pointers, this is a signal to the
  garbage collector that is has permission to collect the
  object if memory is running low.
» You have to maintain own HashTable of Objects
» To understand this pattern better look at Tantalum 3:
  http://projects.developer.nokia.com/Tantalum
public class WeakHashCache {

    protected final Hashtable hash = new Hashtable();

    public Object get(final Object key) {
        final WeakReference reference = (WeakReference) hash.get(key);

        if (reference != null) {
            return reference.get();
        }
        return null;
    }

    public void put(final Object key, final Object value) {
        synchronized (hash) {
            if (key == null) {
                return;
            }
            if (value == null) {
                hash.remove(key);
                return;
            }
            hash.put(key, new WeakReference(value));
        }
    }

    public void remove(final Object key) {
        if (key != null) {
            hash.remove(key);
        }
    }

    public boolean containsKey(final Object key) {
        if (key != null) {
            return hash.containsKey(key);
        }
        return false;
    }

    public int size() {
        return hash.size();
    }

    public void clear() {
        hash.clear();
    }
}
Render Caching
» One of the common performance needs is to make your
  application paint, in particular scroll, smoothly and quickly.
» You can paint items each into their own Image, keeping
  that pre-painted Image in a cache, and reusing it as the
  object moves around the screen. Essentially,
  WeakReference cach of pre-painted Images.
» Can achieve dramatic FPS increase, like in this example
  from 3 to 12 on Asha 305:
» http://www.youtube.com/watch?v=Z2QcnhROFGc
» To understand this pattern better look at Tantalum 3:
  http://projects.developer.nokia.com/Tantalum
File System (Flash Memory) Caching
» Flash memory is slow, but faster then Web.
» Cache downloaded data from previous session. Improve
  startup time of app, by loading from disk cache instead of
  new Web requests.
» RMS and File System (JSR-75) same speed, but with RMS
  no security prompts.
» Can achieve dramatic startup time decrease, like in this
  example from 10 to 2 seconds on Asha 305:
» http://www.youtube.com/watch?v=Cn96lET4moU
File System (Flash Memory) Caching
» Underwater stones: still remember, Flash memory is slow.
» Architect your application to use asynchronous loading
  /saving of data from / to disk cache.
» In Battle Tank example, it was possible to save 28ms in
  each rendered frame, by removing synchronous references
  to flash memory in loop.
» To understand this pattern better look at Tantalum 3:
  http://projects.developer.nokia.com/Tantalum
Hash Acceleration
» Some iterative algorithms are slow. Proper usage of
  collections types of data structures can increase
  performance.
» Vector.contains() is very slow, but Hashtable.containsKey() is
  very fast. Reconsider your algorithms to use Hashtables.
» Usage can be found in very surprising places. For example,
  Font.stringWidth() is slow, but necessary for drawing
  multiline text on Canvas. Creating a Hashtable with the
  width in each character you have used in the Font can
  transform this into a fast operation and increase
  Canvas.paint() speed.
Synchronized vs. Volatile Variables
» When a variable or Object needs to be accessed from more
  than one Thread.
» Marking a variable as volatile is the least restrictive
  approach and can have very high performance because no
  Thread is blocked.
» Only one Thread may enter the synchronized sections at
  any one time.
» Consider atomic operations on two variables. For example, when
  updating firstName and lastName from “John Smith” to “Jane
  Marceau”, do so within a synchronized block to avoid briefly exposing
  the transitional state “Jane Smith” to other threads.
Constants
» We can give the compiler and Proguard more opportunities
  to optimize the code at the compile step, and this will also
  give the ARM processor opportunities for handling these
  variables with more efficient byte codes.
  private static int loopCount = 10;
  private static long startTime = System.currentTimeMillis();
  private static boolean enableImages = true;

  Should be
  private static final int LOOP_COUNT = 10;
  private static final long START_TIME = System.currentTimeMillis();
  private static final boolean ENABLE_IMAGES = true;
Primitives
» Use int instead of short, byte or long.
  for (int i = 0; i < 3000000; i++) {
      short/int/long a = 123;
      short/int/long b = -44;
      short/int/long c = 12;
      a += c;
      b += a;
      c *= b;
  }


  Average times spent in loops on Nokia Asha 305 (obfuscated):
  int:   710 (580) ms
  short: 900 (850) ms 50% slower
  long:  1450 (1150) ms 100% slower
Final in methods
for (int i = 0; i < 1000000; i++) {
    a = finalMethod(1, 2, 3);
}

for (int i = 0; i < 1000000; i++) {
    a = nonFinalMethod(1, 2, 3);
}

public final int finalMethod(final int a, final int b, final int c) {
    final float x = 1.23f, y = 0.05f;
    final float z = x * y;
    final int d = a + b + c;

    return d;
}

public int nonFinalMethod(int a, int b, int c) {
    float x = 1.23f, y = 0.05f;
    float z = x * y;
    int d = a + b + c;

    return d;
}
Final in methods
Average times on a Nokia Asha 305:
finalMethod: 650 ms
nonFinalMethod: 940 ms 45% slower

In this case, the time difference comes from final keyword before
x and y. It is logical because then z value can be precalculated.
The final keywords with parameters a, b, c let us not precalculate
d or anything. And because we don’t use z, it being final does not
help us
Static
» Generally static methods and variables should be faster.
  Oddly, with some combinations of ARM and JVM, instance
  accesses are slightly faster.

   for (int i = 0; i < 1000000; i++) {
       staticMethod();
                                          Average times spent in loops
   }                                      on Nokia Asha 305
   for (int i = 0; i < 1000000; i++) {
       nonStaticMethod();
                                          (obfuscated):
   }

   private static void staticMethod() {   nonStaticMethod: 570 ms
       b++; // static variable
   }                                      staticMethod: 680 ms 20%
   private void nonStaticMethod() {       slower
       a++; // instance variable
   }
String Concatenation
If you are going to concatenate a large number of small Strings,
use:

StringBuffer.append()

instead of the

String +=

operator. String is much slower because every time you
concatenate a string to another with += operator, a new
StringBuffer is created under the hood. Depending on the number
of concatenations, a single explicit StringBuffer can be many times
faster than multiple implicit StringBuffers created by String
addition.
Addition vs. Multiplication vs. Division
for (int i = 0; i < 500000; i++) {
    a = 1.23f;
    b = 1.45f;
    c = 0.004523f;

    c += a;
    a = b + c;
}
for (int i = 0; i < 500000; i++) {
                                     Average times spent in loops
    a = 1.23f;
    b = 1.45f;
                                     on Nokia Asha 305:
    c = 0.004523f;

    c *= a;                          Multiplying: 330 ms
    a = b * c;
}                                    Addition: 360 ms 9% slower
for (int i = 0; i < 500000; i++) {
    a = 1.23f;                       Division: 560 ms 70% slower
    b = 1.45f;
    c = 0.004523f;

    c /= a;
    a = b / c;
}
Switch vs. If
The switch statement in C is implemented as a direct jump which is
extremely fast. In Java on Nokia Series 40 phones, switches are
implemented at the bytecode level as a series of if statements.
Therefore in many cases a switch statement is less efficient than a
manually created series of if..else statements in which the first
positive case is selected as the one which occurs more frequently. If
you prefer to use switch statements for code clarity, then arrange
them so that the most frequent cases appear first.
Hidden References
» All inner classes contain a reference to the parent class.
  Even if your code does not take advantage of this, if you
  pass an inner class to an execution queue such as the event
  dispatch thread (EDT), the parent class cannot be garbage
  collected until the inner class instance has been executed
  and can be garbage collected.
   MyCanvas:
   midlet.getDisplay().callSerially(new Runnable() {

     public void run() {
        System.out.println(“Canvas width: “ +
                MyCanvas.this.getWidth());
       }
   });
Performance summary
» Compare Algorithms
  › Talk to colleagues and pick the best algorithm; having
    the best possible algorithm is the most effective way to
    optimize performance.

» Simple Architecture
  › Keep your architecture simple and to the point without
    extra layers of method calls or objects for artificial
    abstraction. Mobile front end code does not last for
    ever, so over-engineering and excessive abstraction into
    multiple classes will slow you down compared to simple
    use of variables.
Performance summary
» Manage Memory with WeakReference
  Caching
  › Avoid memory problems by always accessing image
    data in memory using a WeakReference Cache.
  › Create a type of virtual memory by duplicating the
    WeakReference cache contents in Flash memory
    (Record Management System) so that you can quickly
    recover items which are no longer available in RAM.
Performance summary
» Use micro-optimizations of the code as habit
  › Know the rules of micro-optimisation for memory
    performance, logic and calculations. Include those as
    you develop, but trust Proguard to add the finishing
    touches.
  › Help Proguard by making everything possible final or
    static final. Avoid static variables in high performance
    loops as they are slower than instance variables.
Performance summary
» Profile your app towards the end of project
  › Profile your application in an emulator.
  › Also test the actual run-time of critical code sections on
    the phone using System.currentTimeMillis() to see and
    carefully measure the effects of your code changes.
›   Extreme Mobile Java
JavaOne 2012          Performance Tuning, User
  San Francisco       Experience, and Architecture
                      Patterns
                       ›   Wednesday, Oct 3, 11:30AM

                       ›   Notel Nikko – Monterey I/II

                       ›   http://tinyurl.com/95moz2l


                  ›   Java for Mobile Devices: New
                      Horizons with Fantastic New
                      Devices
                       ›   Monday, Oct 1, 8:30AM

                       ›   Notel Nikko – Monterey I/II

                       ›   http://tinyurl.com/8lndb3m
Thank you!




@MichaelSamarin

More Related Content

What's hot

JS Fest 2019. Александр Хотемский. Способы распараллеливания тестов в JavaScript
JS Fest 2019. Александр Хотемский. Способы распараллеливания тестов в JavaScriptJS Fest 2019. Александр Хотемский. Способы распараллеливания тестов в JavaScript
JS Fest 2019. Александр Хотемский. Способы распараллеливания тестов в JavaScriptJSFestUA
 
Distributed automation selcamp2016
Distributed automation selcamp2016Distributed automation selcamp2016
Distributed automation selcamp2016aragavan
 
High Performance on Drupal 7
High Performance on Drupal 7High Performance on Drupal 7
High Performance on Drupal 7Exove
 
Autoscaled Distributed Automation Expedia Know How
Autoscaled Distributed Automation Expedia Know HowAutoscaled Distributed Automation Expedia Know How
Autoscaled Distributed Automation Expedia Know Howaragavan
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsDror Bereznitsky
 
Developing distributed analysis pipelines with shared community resources usi...
Developing distributed analysis pipelines with shared community resources usi...Developing distributed analysis pipelines with shared community resources usi...
Developing distributed analysis pipelines with shared community resources usi...Brad Chapman
 
Gopher in performance_tales_ms_go_cracow
Gopher in performance_tales_ms_go_cracowGopher in performance_tales_ms_go_cracow
Gopher in performance_tales_ms_go_cracowMateuszSzczyrzyca
 
Dconrails Gecco Presentation
Dconrails Gecco PresentationDconrails Gecco Presentation
Dconrails Gecco PresentationJuan J. Merelo
 
Planning to Fail #phpne13
Planning to Fail #phpne13Planning to Fail #phpne13
Planning to Fail #phpne13Dave Gardner
 
Multi Core Playground
Multi Core PlaygroundMulti Core Playground
Multi Core PlaygroundESUG
 
Operational Efficiency Hacks Web20 Expo2009
Operational Efficiency Hacks Web20 Expo2009Operational Efficiency Hacks Web20 Expo2009
Operational Efficiency Hacks Web20 Expo2009John Allspaw
 
Autoscaled Distributed Automation using AWS at Selenium London MeetUp
Autoscaled Distributed Automation using AWS at Selenium London MeetUpAutoscaled Distributed Automation using AWS at Selenium London MeetUp
Autoscaled Distributed Automation using AWS at Selenium London MeetUparagavan
 
Optimizing Large Scenes in Unity
Optimizing Large Scenes in UnityOptimizing Large Scenes in Unity
Optimizing Large Scenes in UnityNoam Gat
 
Unity Internals: Memory and Performance
Unity Internals: Memory and PerformanceUnity Internals: Memory and Performance
Unity Internals: Memory and PerformanceDevGAMM Conference
 

What's hot (15)

JS Fest 2019. Александр Хотемский. Способы распараллеливания тестов в JavaScript
JS Fest 2019. Александр Хотемский. Способы распараллеливания тестов в JavaScriptJS Fest 2019. Александр Хотемский. Способы распараллеливания тестов в JavaScript
JS Fest 2019. Александр Хотемский. Способы распараллеливания тестов в JavaScript
 
Distributed automation selcamp2016
Distributed automation selcamp2016Distributed automation selcamp2016
Distributed automation selcamp2016
 
High Performance on Drupal 7
High Performance on Drupal 7High Performance on Drupal 7
High Performance on Drupal 7
 
Autoscaled Distributed Automation Expedia Know How
Autoscaled Distributed Automation Expedia Know HowAutoscaled Distributed Automation Expedia Know How
Autoscaled Distributed Automation Expedia Know How
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance Diagnostics
 
Developing distributed analysis pipelines with shared community resources usi...
Developing distributed analysis pipelines with shared community resources usi...Developing distributed analysis pipelines with shared community resources usi...
Developing distributed analysis pipelines with shared community resources usi...
 
Gopher in performance_tales_ms_go_cracow
Gopher in performance_tales_ms_go_cracowGopher in performance_tales_ms_go_cracow
Gopher in performance_tales_ms_go_cracow
 
Dconrails Gecco Presentation
Dconrails Gecco PresentationDconrails Gecco Presentation
Dconrails Gecco Presentation
 
Planning to Fail #phpne13
Planning to Fail #phpne13Planning to Fail #phpne13
Planning to Fail #phpne13
 
Multi Core Playground
Multi Core PlaygroundMulti Core Playground
Multi Core Playground
 
Operational Efficiency Hacks Web20 Expo2009
Operational Efficiency Hacks Web20 Expo2009Operational Efficiency Hacks Web20 Expo2009
Operational Efficiency Hacks Web20 Expo2009
 
Autoscaled Distributed Automation using AWS at Selenium London MeetUp
Autoscaled Distributed Automation using AWS at Selenium London MeetUpAutoscaled Distributed Automation using AWS at Selenium London MeetUp
Autoscaled Distributed Automation using AWS at Selenium London MeetUp
 
Optimizing Large Scenes in Unity
Optimizing Large Scenes in UnityOptimizing Large Scenes in Unity
Optimizing Large Scenes in Unity
 
Unity Internals: Memory and Performance
Unity Internals: Memory and PerformanceUnity Internals: Memory and Performance
Unity Internals: Memory and Performance
 
Ha & drs gotcha's
Ha & drs gotcha'sHa & drs gotcha's
Ha & drs gotcha's
 

Similar to Designing and coding Series 40 Java apps for high performance

Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK toolsHaribabu Nandyal Padmanaban
 
Machine Learning With H2O vs SparkML
Machine Learning With H2O vs SparkMLMachine Learning With H2O vs SparkML
Machine Learning With H2O vs SparkMLArnab Biswas
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android ApplicationsLokesh Ponnada
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performancekaven yan
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsJulien Lecomte
 
performance optimization: Memory
performance optimization: Memoryperformance optimization: Memory
performance optimization: Memory晓东 杜
 
Infrastructure as Code, Theory Crash Course
Infrastructure as Code, Theory Crash CourseInfrastructure as Code, Theory Crash Course
Infrastructure as Code, Theory Crash CourseDr. Sven Balnojan
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performanceRoger Xia
 
Commit to excellence - Java in containers
Commit to excellence - Java in containersCommit to excellence - Java in containers
Commit to excellence - Java in containersRed Hat Developers
 
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Elixir Club
 
State of Java Elasticity. Tuning Java Efficiency - GIDS.JAVA LIVE 2020
State of Java Elasticity. Tuning Java Efficiency - GIDS.JAVA LIVE 2020State of Java Elasticity. Tuning Java Efficiency - GIDS.JAVA LIVE 2020
State of Java Elasticity. Tuning Java Efficiency - GIDS.JAVA LIVE 2020Jelastic Multi-Cloud PaaS
 
Shorten Device Boot Time for Automotive IVI and Navigation Systems
Shorten Device Boot Time for Automotive IVI and Navigation SystemsShorten Device Boot Time for Automotive IVI and Navigation Systems
Shorten Device Boot Time for Automotive IVI and Navigation SystemsNational Cheng Kung University
 
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyFast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyKyle Drake
 
From Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceFrom Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceSebastian Springer
 
Low latency in java 8 v5
Low latency in java 8 v5Low latency in java 8 v5
Low latency in java 8 v5Peter Lawrey
 
Efficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java ApplicationsEfficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java ApplicationsPhillip Koza
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang YoonJesang Yoon
 
Automated Scaling of Microservice Stacks for JavaEE Applications
Automated Scaling of Microservice Stacks for JavaEE ApplicationsAutomated Scaling of Microservice Stacks for JavaEE Applications
Automated Scaling of Microservice Stacks for JavaEE ApplicationsJelastic Multi-Cloud PaaS
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrencyaviade
 

Similar to Designing and coding Series 40 Java apps for high performance (20)

Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Machine Learning With H2O vs SparkML
Machine Learning With H2O vs SparkMLMachine Learning With H2O vs SparkML
Machine Learning With H2O vs SparkML
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android Applications
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
performance optimization: Memory
performance optimization: Memoryperformance optimization: Memory
performance optimization: Memory
 
Infrastructure as Code, Theory Crash Course
Infrastructure as Code, Theory Crash CourseInfrastructure as Code, Theory Crash Course
Infrastructure as Code, Theory Crash Course
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
 
Commit to excellence - Java in containers
Commit to excellence - Java in containersCommit to excellence - Java in containers
Commit to excellence - Java in containers
 
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
 
State of Java Elasticity. Tuning Java Efficiency - GIDS.JAVA LIVE 2020
State of Java Elasticity. Tuning Java Efficiency - GIDS.JAVA LIVE 2020State of Java Elasticity. Tuning Java Efficiency - GIDS.JAVA LIVE 2020
State of Java Elasticity. Tuning Java Efficiency - GIDS.JAVA LIVE 2020
 
Shorten Device Boot Time for Automotive IVI and Navigation Systems
Shorten Device Boot Time for Automotive IVI and Navigation SystemsShorten Device Boot Time for Automotive IVI and Navigation Systems
Shorten Device Boot Time for Automotive IVI and Navigation Systems
 
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyFast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
 
From Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceFrom Zero to Hero – Web Performance
From Zero to Hero – Web Performance
 
Low latency in java 8 v5
Low latency in java 8 v5Low latency in java 8 v5
Low latency in java 8 v5
 
Efficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java ApplicationsEfficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java Applications
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoon
 
Automated Scaling of Microservice Stacks for JavaEE Applications
Automated Scaling of Microservice Stacks for JavaEE ApplicationsAutomated Scaling of Microservice Stacks for JavaEE Applications
Automated Scaling of Microservice Stacks for JavaEE Applications
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
 

More from Microsoft Mobile Developer

Intro to Nokia X software platform 2.0 and tools
Intro to Nokia X software platform 2.0 and toolsIntro to Nokia X software platform 2.0 and tools
Intro to Nokia X software platform 2.0 and toolsMicrosoft Mobile Developer
 
Location based services for Nokia X and Nokia Asha using Geo2tag
Location based services for Nokia X and Nokia Asha using Geo2tagLocation based services for Nokia X and Nokia Asha using Geo2tag
Location based services for Nokia X and Nokia Asha using Geo2tagMicrosoft Mobile Developer
 
Lumia App Labs: Lessons learned from 50 windows phone 8 design consultations
Lumia App Labs: Lessons learned from 50 windows phone 8 design consultationsLumia App Labs: Lessons learned from 50 windows phone 8 design consultations
Lumia App Labs: Lessons learned from 50 windows phone 8 design consultationsMicrosoft Mobile Developer
 
Windows Phone 8 speech: parliamo con la nostra app
Windows Phone 8 speech: parliamo con la nostra appWindows Phone 8 speech: parliamo con la nostra app
Windows Phone 8 speech: parliamo con la nostra appMicrosoft Mobile Developer
 
La pubblicazione di un'applicazione sullo store
La pubblicazione di un'applicazione sullo storeLa pubblicazione di un'applicazione sullo store
La pubblicazione di un'applicazione sullo storeMicrosoft Mobile Developer
 
Il pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoIl pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoMicrosoft Mobile Developer
 

More from Microsoft Mobile Developer (20)

Intro to Nokia X software platform 2.0 and tools
Intro to Nokia X software platform 2.0 and toolsIntro to Nokia X software platform 2.0 and tools
Intro to Nokia X software platform 2.0 and tools
 
Lumia App Labs: Lumia SensorCore SDK beta
Lumia App Labs: Lumia SensorCore SDK betaLumia App Labs: Lumia SensorCore SDK beta
Lumia App Labs: Lumia SensorCore SDK beta
 
Nokia Asha from idea to app - Imaging
Nokia Asha from idea to app - ImagingNokia Asha from idea to app - Imaging
Nokia Asha from idea to app - Imaging
 
Healthcare apps for Nokia X and Nokia Asha
Healthcare apps for Nokia X and Nokia AshaHealthcare apps for Nokia X and Nokia Asha
Healthcare apps for Nokia X and Nokia Asha
 
Push notifications on Nokia X
Push notifications on Nokia XPush notifications on Nokia X
Push notifications on Nokia X
 
DIY Nokia Asha app usability studies
DIY Nokia Asha app usability studiesDIY Nokia Asha app usability studies
DIY Nokia Asha app usability studies
 
Lessons learned from Nokia X UI reviews
Lessons learned from Nokia X UI reviewsLessons learned from Nokia X UI reviews
Lessons learned from Nokia X UI reviews
 
Location based services for Nokia X and Nokia Asha using Geo2tag
Location based services for Nokia X and Nokia Asha using Geo2tagLocation based services for Nokia X and Nokia Asha using Geo2tag
Location based services for Nokia X and Nokia Asha using Geo2tag
 
HERE Maps for the Nokia X platform
HERE Maps for the Nokia X platformHERE Maps for the Nokia X platform
HERE Maps for the Nokia X platform
 
Nokia In-App Payment - UX considerations
Nokia In-App Payment - UX considerationsNokia In-App Payment - UX considerations
Nokia In-App Payment - UX considerations
 
Introduction to Nokia Asha SDK 1.2 (beta)
Introduction to Nokia Asha SDK 1.2 (beta)Introduction to Nokia Asha SDK 1.2 (beta)
Introduction to Nokia Asha SDK 1.2 (beta)
 
UX considerations when porting to Nokia X
UX considerations when porting to Nokia XUX considerations when porting to Nokia X
UX considerations when porting to Nokia X
 
Kids' games and educational app design
Kids' games and educational app designKids' games and educational app design
Kids' games and educational app design
 
Nokia X: opportunities for developers
Nokia X: opportunities for developersNokia X: opportunities for developers
Nokia X: opportunities for developers
 
Lumia App Labs: Nokia Imaging SDK 1.1
Lumia App Labs: Nokia Imaging SDK 1.1Lumia App Labs: Nokia Imaging SDK 1.1
Lumia App Labs: Nokia Imaging SDK 1.1
 
Intro to Nokia X software platform and tools
Intro to Nokia X software platform and toolsIntro to Nokia X software platform and tools
Intro to Nokia X software platform and tools
 
Lumia App Labs: Lessons learned from 50 windows phone 8 design consultations
Lumia App Labs: Lessons learned from 50 windows phone 8 design consultationsLumia App Labs: Lessons learned from 50 windows phone 8 design consultations
Lumia App Labs: Lessons learned from 50 windows phone 8 design consultations
 
Windows Phone 8 speech: parliamo con la nostra app
Windows Phone 8 speech: parliamo con la nostra appWindows Phone 8 speech: parliamo con la nostra app
Windows Phone 8 speech: parliamo con la nostra app
 
La pubblicazione di un'applicazione sullo store
La pubblicazione di un'applicazione sullo storeLa pubblicazione di un'applicazione sullo store
La pubblicazione di un'applicazione sullo store
 
Il pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoIl pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progetto
 

Recently uploaded

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 

Recently uploaded (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 

Designing and coding Series 40 Java apps for high performance

  • 1. Series 40 Developer Training Michael Samarin Paul Houghton Timo Saarinen Designing and coding Series 40 Java apps for high performance Futurice Ltd
  • 2. Today’s Topics » Performance Basics on Series 40 » Mobile Front End Architecture Patterns » Choosing GUI, Caching, Threading » Low Level “Micro” Performance Optimization
  • 3. Miller, R. B. (1968) Response time in man-computer conversational transactions. Proc. AFIPS Fall Joint Computer ConferenceVol. 33, 267-277 » 0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.
  • 4. » 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data. » 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.
  • 5. Choosing GUI Strategy » LCDUI Forms. » Canvas » GameCanvas » LWUIT
  • 6. LCDUI Forms » Fast, simple and standard way of making UI. » On full touch Asha very attractive looking and have huge UX improvements. » Not as fast as Canvas. Animation on a Form is much slower than on a Canvas, and there is no way to influence the vertical scroll position, animate transitions between screen, or shift to a full screen view. You can, however, slightly increase the performance when changing screens by using just one Form and re- populating it with new Items. » http://www.developer.nokia.com/Resources/Library/Full_Touch
  • 7. Canvas » Highly customizable way of making UI. » You have to take care of render timing yourself, or you can use Nokia’s FrameAnimator class to quickly create effects such as kinetic scrolling. » Any part of your code can call Canvas.repaint() to signal that painting should occur soon. » The most important performance tip for navigating through a Canvas-based UI is to implement your own View class to represent each screen, and paint all Views on one Canvas rather than switching from one Canvas to another, which can be slow and does not give you the possibility of animating the transition for smooth effect.
  • 8. GameCanvas » GameCanvas is double buffered with more control over the painting cycle and threading. » Unlike Canvas, you should create your own Thread, which calls GameCanvas.paint() directly to fill the graphics buffer, and then GameCanvas.flushGraphics() to instantly blit the graphics buffer onto the screen.
  • 9. LWUIT » LWUIT (Lightweight User Interface Toolkit) is a toolkit for creating SWING-like applications without some of the complexity of SWING. » Like Form, it offers basic components, but it adds to this better layouts, styles and theming, bundling own fonts into your application, and animated screen transitions. » LWUIT is implemented on top of a Canvas, but it is a large and complex library written to be a general purpose replacement for the default UI on many different phones. » LWUIT and the associated themes and any fonts you include quickly make your JAR file grow quite large. » http://projects.developer.nokia.com/LWUIT_for_Series_40
  • 10. Heap Memory » On Series 40 only from 2 to 4 MB. » Instances of classes (objects) and primitive types are created in the heap. » Total number of methods in classes loaded by JVM has a direct impact on how much heap space is left for other data. These memory allocations are permanent for the runtime of the application and are not dynamically unloaded by the JVM once a class is no longer in use.
  • 11. Recursive Algorithms and Stack Memory » Variables passed as arguments to a method are passed on the current thread’s stack. Method variables of primitive types are also allocated on the stack. » Recursive algorithms are algorithms where a method calls itself in a loop to complete a task. As a result, they create multiple stack frames. › They use a lot of stack memory. The same method is called repeatedly, and only as the application completes does it unwind the queued stack frames. This extra stack memory is often not useful, and stack memory per thread is limited and such heavy stack use may well cause an OutOfMemoryException well before you are actually out of heap memory. › Recursive algorithms can be slow. Each method call includes a certain amount of overhead, which is not really necessary since a recursive algorithm can be unwound into a non-recursive equivalent loop that does not include the relatively heavy method call.
  • 12. › Provides basic “free” optimization › Fixes code redundancy and pre-calculate things Compile Time whenever possible Optimization › Minimizes memory usage and › Should be last step in Obfuscation building apps – takes time and makes debugging difficult › Doesn’t fix wrong architecture
  • 15. Obfuscation Example: Battle Tank https://projects.developer.nokia.com/JMEBattleTank › JAR File size decreased by 4% (889 -> 852 kB) › RAM usage decreased by 14% (161 -> 138 kB)
  • 16. Architecture changes » Carefully consider architecture of your drawing loop and input loops and decouple them whenever possible. » Example: panorama drawing and sensor driving loop. » Original example: » http://www.youtube.com/watch?v=PfW4BVHgri8 » After optimization: » http://www.youtube.com/watch?v=xSRYVYrNNMI
  • 17. WeakReference object Caching » Best pattern for using all available heap memory, but never running into the dreaded OutOfMemoryError. » CLDC 1.1 WeakReference » When an object is referenced by a WeakReference, and not using traditional Object pointers, this is a signal to the garbage collector that is has permission to collect the object if memory is running low. » You have to maintain own HashTable of Objects » To understand this pattern better look at Tantalum 3: http://projects.developer.nokia.com/Tantalum
  • 18. public class WeakHashCache { protected final Hashtable hash = new Hashtable(); public Object get(final Object key) { final WeakReference reference = (WeakReference) hash.get(key); if (reference != null) { return reference.get(); } return null; } public void put(final Object key, final Object value) { synchronized (hash) { if (key == null) { return; } if (value == null) { hash.remove(key); return; } hash.put(key, new WeakReference(value)); } } public void remove(final Object key) { if (key != null) { hash.remove(key); } } public boolean containsKey(final Object key) { if (key != null) { return hash.containsKey(key); } return false; } public int size() { return hash.size(); } public void clear() { hash.clear(); } }
  • 19. Render Caching » One of the common performance needs is to make your application paint, in particular scroll, smoothly and quickly. » You can paint items each into their own Image, keeping that pre-painted Image in a cache, and reusing it as the object moves around the screen. Essentially, WeakReference cach of pre-painted Images. » Can achieve dramatic FPS increase, like in this example from 3 to 12 on Asha 305: » http://www.youtube.com/watch?v=Z2QcnhROFGc » To understand this pattern better look at Tantalum 3: http://projects.developer.nokia.com/Tantalum
  • 20. File System (Flash Memory) Caching » Flash memory is slow, but faster then Web. » Cache downloaded data from previous session. Improve startup time of app, by loading from disk cache instead of new Web requests. » RMS and File System (JSR-75) same speed, but with RMS no security prompts. » Can achieve dramatic startup time decrease, like in this example from 10 to 2 seconds on Asha 305: » http://www.youtube.com/watch?v=Cn96lET4moU
  • 21. File System (Flash Memory) Caching » Underwater stones: still remember, Flash memory is slow. » Architect your application to use asynchronous loading /saving of data from / to disk cache. » In Battle Tank example, it was possible to save 28ms in each rendered frame, by removing synchronous references to flash memory in loop. » To understand this pattern better look at Tantalum 3: http://projects.developer.nokia.com/Tantalum
  • 22. Hash Acceleration » Some iterative algorithms are slow. Proper usage of collections types of data structures can increase performance. » Vector.contains() is very slow, but Hashtable.containsKey() is very fast. Reconsider your algorithms to use Hashtables. » Usage can be found in very surprising places. For example, Font.stringWidth() is slow, but necessary for drawing multiline text on Canvas. Creating a Hashtable with the width in each character you have used in the Font can transform this into a fast operation and increase Canvas.paint() speed.
  • 23. Synchronized vs. Volatile Variables » When a variable or Object needs to be accessed from more than one Thread. » Marking a variable as volatile is the least restrictive approach and can have very high performance because no Thread is blocked. » Only one Thread may enter the synchronized sections at any one time. » Consider atomic operations on two variables. For example, when updating firstName and lastName from “John Smith” to “Jane Marceau”, do so within a synchronized block to avoid briefly exposing the transitional state “Jane Smith” to other threads.
  • 24. Constants » We can give the compiler and Proguard more opportunities to optimize the code at the compile step, and this will also give the ARM processor opportunities for handling these variables with more efficient byte codes. private static int loopCount = 10; private static long startTime = System.currentTimeMillis(); private static boolean enableImages = true; Should be private static final int LOOP_COUNT = 10; private static final long START_TIME = System.currentTimeMillis(); private static final boolean ENABLE_IMAGES = true;
  • 25. Primitives » Use int instead of short, byte or long. for (int i = 0; i < 3000000; i++) { short/int/long a = 123; short/int/long b = -44; short/int/long c = 12; a += c; b += a; c *= b; } Average times spent in loops on Nokia Asha 305 (obfuscated): int: 710 (580) ms short: 900 (850) ms 50% slower long: 1450 (1150) ms 100% slower
  • 26. Final in methods for (int i = 0; i < 1000000; i++) { a = finalMethod(1, 2, 3); } for (int i = 0; i < 1000000; i++) { a = nonFinalMethod(1, 2, 3); } public final int finalMethod(final int a, final int b, final int c) { final float x = 1.23f, y = 0.05f; final float z = x * y; final int d = a + b + c; return d; } public int nonFinalMethod(int a, int b, int c) { float x = 1.23f, y = 0.05f; float z = x * y; int d = a + b + c; return d; }
  • 27. Final in methods Average times on a Nokia Asha 305: finalMethod: 650 ms nonFinalMethod: 940 ms 45% slower In this case, the time difference comes from final keyword before x and y. It is logical because then z value can be precalculated. The final keywords with parameters a, b, c let us not precalculate d or anything. And because we don’t use z, it being final does not help us
  • 28. Static » Generally static methods and variables should be faster. Oddly, with some combinations of ARM and JVM, instance accesses are slightly faster. for (int i = 0; i < 1000000; i++) { staticMethod(); Average times spent in loops } on Nokia Asha 305 for (int i = 0; i < 1000000; i++) { nonStaticMethod(); (obfuscated): } private static void staticMethod() { nonStaticMethod: 570 ms b++; // static variable } staticMethod: 680 ms 20% private void nonStaticMethod() { slower a++; // instance variable }
  • 29. String Concatenation If you are going to concatenate a large number of small Strings, use: StringBuffer.append() instead of the String += operator. String is much slower because every time you concatenate a string to another with += operator, a new StringBuffer is created under the hood. Depending on the number of concatenations, a single explicit StringBuffer can be many times faster than multiple implicit StringBuffers created by String addition.
  • 30. Addition vs. Multiplication vs. Division for (int i = 0; i < 500000; i++) { a = 1.23f; b = 1.45f; c = 0.004523f; c += a; a = b + c; } for (int i = 0; i < 500000; i++) { Average times spent in loops a = 1.23f; b = 1.45f; on Nokia Asha 305: c = 0.004523f; c *= a; Multiplying: 330 ms a = b * c; } Addition: 360 ms 9% slower for (int i = 0; i < 500000; i++) { a = 1.23f; Division: 560 ms 70% slower b = 1.45f; c = 0.004523f; c /= a; a = b / c; }
  • 31. Switch vs. If The switch statement in C is implemented as a direct jump which is extremely fast. In Java on Nokia Series 40 phones, switches are implemented at the bytecode level as a series of if statements. Therefore in many cases a switch statement is less efficient than a manually created series of if..else statements in which the first positive case is selected as the one which occurs more frequently. If you prefer to use switch statements for code clarity, then arrange them so that the most frequent cases appear first.
  • 32. Hidden References » All inner classes contain a reference to the parent class. Even if your code does not take advantage of this, if you pass an inner class to an execution queue such as the event dispatch thread (EDT), the parent class cannot be garbage collected until the inner class instance has been executed and can be garbage collected. MyCanvas: midlet.getDisplay().callSerially(new Runnable() { public void run() { System.out.println(“Canvas width: “ + MyCanvas.this.getWidth()); } });
  • 33. Performance summary » Compare Algorithms › Talk to colleagues and pick the best algorithm; having the best possible algorithm is the most effective way to optimize performance. » Simple Architecture › Keep your architecture simple and to the point without extra layers of method calls or objects for artificial abstraction. Mobile front end code does not last for ever, so over-engineering and excessive abstraction into multiple classes will slow you down compared to simple use of variables.
  • 34. Performance summary » Manage Memory with WeakReference Caching › Avoid memory problems by always accessing image data in memory using a WeakReference Cache. › Create a type of virtual memory by duplicating the WeakReference cache contents in Flash memory (Record Management System) so that you can quickly recover items which are no longer available in RAM.
  • 35. Performance summary » Use micro-optimizations of the code as habit › Know the rules of micro-optimisation for memory performance, logic and calculations. Include those as you develop, but trust Proguard to add the finishing touches. › Help Proguard by making everything possible final or static final. Avoid static variables in high performance loops as they are slower than instance variables.
  • 36. Performance summary » Profile your app towards the end of project › Profile your application in an emulator. › Also test the actual run-time of critical code sections on the phone using System.currentTimeMillis() to see and carefully measure the effects of your code changes.
  • 37. Extreme Mobile Java JavaOne 2012 Performance Tuning, User San Francisco Experience, and Architecture Patterns › Wednesday, Oct 3, 11:30AM › Notel Nikko – Monterey I/II › http://tinyurl.com/95moz2l › Java for Mobile Devices: New Horizons with Fantastic New Devices › Monday, Oct 1, 8:30AM › Notel Nikko – Monterey I/II › http://tinyurl.com/8lndb3m