Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Code Optimization of Android Programming

Code Optimization of Android Programming

The presentation was given on EATL Apps Competition top 15 grooming session.

A N M Bazlur Rahman

March 08, 2013
Tweet

More Decks by A N M Bazlur Rahman

Other Decks in Programming

Transcript

  1. Basic Two Principle • Don't do work that you don't

    need to do. • Don't allocate memory if you can avoid it.
  2. Avoid Creating Unnecessary Object Object creation is never free. you

    should avoid creating object instance you don't need to. Ex- use String result = ""; for (String s : hugeArray) { result = result + s; } instead of StringBuilder sb = new StringBuilder(); for (String s : hugeArray) { sb.append(s); } String result = sb.toString();
  3. Tips • An array of ints is a much better

    than an array of Integer objects. • two parallel arrays of ints are lot more efficient than int[][] • use class Container{ Object a, Object b } Container [] container = new ...... instead of Container{ Object[] a; Object[] b; }
  4. Use static final for constants static int intVal = 42;

    static String strVal = "Hello, world!"; The compiler generates a class initializer method, called <clinit>, that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the classfile string constant table for strVal. When these values are referenced later on, they are accessed with field lookups. We can improve matters with the "final" keyword: static final int intVal = 42; static final String strVal = "Hello, world!";
  5. Use Enhanced for Loop static class Foo { int mSplat;

    } Foo[] mArray = ... public void zero() { int sum = 0; for (int i = 0; i < mArray.length; ++i) { sum += mArray[i].mSplat; } } public void one() { int sum = 0; Foo[] localArray = mArray; int len = localArray.length; for (int i = 0; i < len; ++i) { sum += localArray[i].mSplat; } }
  6. public void two() { int sum = 0; for (Foo

    a : mArray) { sum += a.mSplat; } } zero() is slowest. one() is faster two() faster
  7. Consider Package Instead of Access with private Inner Class public

    class Foo { private class Inner { void stuff() { Foo.this.doStuff(Foo.this.mValue); } } private int mValue; public void run() { Inner in = new Inner(); mValue = 27; in.stuff(); } private void doStuff(int value) { System.out.println("Value is " + value); } }
  8. static int Foo.access$100(Foo foo) { return foo.mValue; } static void

    Foo.access$200(Foo foo, int value) { foo.doStuff(value); }
  9. Avoid Using floating point • floating-point is about 2x slower

    than integer on Android-powered devices.
  10. Load view on Demand ◦ use ViewStub <ViewStub android:id="@+id/stub_import" android:inflatedId="@+id/panel_import"

    android:layout="@layout/progress_overlay" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> (ViewStub) findViewById(R.id.stub_import)).setVisibility(View. VISIBLE); // or View importPanel = ((ViewStub) findViewById(R.id.stub_import)). inflate();
  11. Don't Ignore Exceptions void setServerPort(String value) { try { serverPort

    = Integer.parseInt(value); } catch (NumberFormatException e) { } } void setServerPort(String value) { try { serverPort = Integer.parseInt(value); } catch (NumberFormatException e) { throw new RuntimeException("port " + value " is invalid, ", e); } } Anytime somebody has an empty catch clause they should have a creepy feeling. There are definitely times when it is actually the correct thing to do, but at least you have to think about it. In Java you can't escape the creepy feeling. - James Gosling
  12. Don't Catch Generic Exception try { someComplicatedIOFunction(); // may throw

    IOException someComplicatedParsingFunction(); // may throw ParsingException someComplicatedSecurityFunction(); // may throw SecurityException // phew, made it all the way } catch (Exception e) { // I'll just catch all exceptions handleError(); // with one generic handler! }
  13. Order Import Statements The ordering of import statements is: 1.

    Android imports 2. Imports from third parties (com, junit, net, org) 3. java and javax
  14. Naming Conventions Meaningful names: all name used in code should

    be meaningful, methods name should be like what they do, for say calculate() which perform some calculation. And naming should be in English spelling. Naming should be avoid abbreviations. Should use meaningful name while naming class name, variable name, constant name. Like - class name → AddressDetails method name → addAddressDetails variable name → username constant name → DEAFULT_VALUE
  15. Familiar Names : existing terminology should be used like customer,

    clients etc Case : Java is case sensitive. So username and Username is different. But it should no use same name that differs only in case. Package name: package name must be lower case. Like → iit.bit.rokon.com Class name: class name must be start with upper case. Class name should be noun. Class name can contain multiple words. This case they are linked like → AddressDetails. Every word should start with upper case letter. Interface name: interface name should be like class name. And should use none or adjective while naming interface.
  16. Method name: first letter must be lower case and capitalize

    first letter of each subsequent word that appears in a method name. And method name should be verb. In the case of accessor method, we should use JavaBean convention. Like getter and setters. Example - class User{ private String username; public void setUsername(String username){ this.username = username; } public String getUsername(){ return username; } } Variable name: Variable name should be noun and should be start with lowercase and capitalize first letter of each subsequent word that appears. Constant Name: Constant name should use uppercase letters for each word and separate each pair of words with and underscore. Example - public static final int DEAFULT_VALUE = 1;
  17. Treat Acronyms as Words Treat acronyms and abbreviations as words

    in naming variables, methods, and classes. The names are much more readable: Good Bad XmlHttpRequest XMLHTTPRequest getCustomerId getCustomerID class Html class HTML String url String URL long id long ID
  18. Some Useful Links and Blog Post Activities: http://developer.android.com/guide/components/activities.html http://developer.android.com/training/basics/activity-lifecycle/recreating.html Work

    with Location: http://developer.android.com/guide/topics/location/strategies.html Saving Persistent State: http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState http://www.techotopia.com/index.php/Saving_and_Restoring_the_User_Interface_State_of_an_Android_Activity Threads : Handler & AsyncTask http://developer.android.com/guide/components/processes-and-threads.html#Threads http://stackoverflow.com/questions/6964011/handler-vs-asynctask-vs-thread http://developer.android.com/guide/topics/resources/runtime-changes.html (Runtime Change) Loopers and Handlers https://developer.android.com/training/multiple-threads/communicate-ui.html http://blog.xandroid.mobi/android-tutorial/tutorial-collection/loopers-and-handlers-in-android/
  19. Displaying Bitmaps Efficiently: http://developer.android.com/training/displaying-bitmaps/index.html http://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue-while-loading-an-image-to-a-bitmap- object/823966#823966 Android Development, rosscode.com :

    http://www.rosscode.com/blog/index.php?title=android-development-part-3-wiring-up-roboguice&more=1&c=1&tb=1&pb=1 Dialogs http://developer.android.com/design/building-blocks/dialogs.html http://developer.android.com/guide/topics/ui/dialogs.html Reusing Layouts http://developer.android.com/training/improving-layouts/reusing-layouts.html Android Standard Coding Guideline: http://source.android.com/source/code-style.html
  20. Android Asynchronous Http Client http://loopj.com/android-async-http/ https://github.com/loopj/android-async-http Features • Make asynchronous

    HTTP requests, handle responses in anonymous callbacks • HTTP requests happen outside the UI thread • Requests use a threadpool to cap concurrent resource usage • GET/POST params builder (RequestParams) • Multipart file uploads with no additional third party libraries • Tiny size overhead to your application, only 25kb for everything • Automatic smart request retries optimized for spotty mobile connections • Automatic gzip response decoding support for super-fast requests • Binary file (images etc) downloading with BinaryHttpResponseHandler • Built-in response parsing into JSON with JsonHttpResponseHandler • Persistent cookie store, saves cookies into your app’s SharedPreferences