Slide 1

Slide 1 text

Code Optimization Bazlur Rahman Rokon @bazlur_rahman

Slide 2

Slide 2 text

Basic Two Principle ● Don't do work that you don't need to do. ● Don't allocate memory if you can avoid it.

Slide 3

Slide 3 text

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();

Slide 4

Slide 4 text

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; }

Slide 5

Slide 5 text

Use static final for constants static int intVal = 42; static String strVal = "Hello, world!"; The compiler generates a class initializer method, called , 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!";

Slide 6

Slide 6 text

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; } }

Slide 7

Slide 7 text

public void two() { int sum = 0; for (Foo a : mArray) { sum += a.mSplat; } } zero() is slowest. one() is faster two() faster

Slide 8

Slide 8 text

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); } }

Slide 9

Slide 9 text

static int Foo.access$100(Foo foo) { return foo.mValue; } static void Foo.access$200(Foo foo, int value) { foo.doStuff(value); }

Slide 10

Slide 10 text

Avoid Using floating point ● floating-point is about 2x slower than integer on Android-powered devices.

Slide 11

Slide 11 text

Know and Use Libraries example- System.arraycopy() is 9x faster than hand written array copying code

Slide 12

Slide 12 text

Improving Layout Performance Use: Hierarchy Viewer And Layoutopt http://developer.android. com/tools/help/hierarchy-viewer.html http://developer.android. com/tools/debugging/debugging-ui. html#layoutopt

Slide 13

Slide 13 text

Load view on Demand ○ use ViewStub (ViewStub) findViewById(R.id.stub_import)).setVisibility(View. VISIBLE); // or View importPanel = ((ViewStub) findViewById(R.id.stub_import)). inflate();

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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! }

Slide 16

Slide 16 text

Use Fully Qualified imports use import foo.Bar; instead of import foo.*;

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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.

Slide 20

Slide 20 text

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;

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

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/

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

Sample & Standard Code Example: http://shelves.googlecode.com/svn/trunk/Shelves/ http://code.google.com/p/mytracks/source/browse/MyTracks/ https://github.com/todoroo/astrid/tree/master/astrid https://github.com/facebook/facebook-android-sdk/tree/master/facebook https://github.com/jfeinstein10/SlidingMenu

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

RoboGuice https://github.com/roboguice/roboguice/wiki

Slide 27

Slide 27 text

Thanks