本人从事java服务器端开发已经有6,7年了,最近这一年多转去作Android开发。到今天以为应该把本身的一些感觉写下来,供之后参考。 java
1. Java bean的定义 数组
咱们通常定义一个java bean,都是用以下的代码: 服务器
public class User { private String name; public void setName(String name) { this.name = name; } public String getName() { return this.name; } }
在Android开发中,咱们通常这样定义一个java bean: ide
public class User { public String name; }
在Android的官方开发文档中这样说到: 性能
In native languages like C++ it's common practice to use getters (i = getCount()) instead of accessing the field directly (i = mCount). This is an excellent habit for C++ and is often practiced in other object oriented languages like C# and Java, because the compiler can usually inline the access, and if you need to restrict or debug field access you can add the code at any time.而对Android开发来讲:
However, this is a bad idea on Android. Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.
没有JIT的话,直接访问成员的速度是经过getter/setter访问速度是3倍。有JIT的话,这个数字是7倍。 学习
2. 尽可能少的建立临时对象,尽可能使用基本类型 this
在服务器端开发的时候,咱们不多会注意这个问题。可是在Android开发中,这些就是咱们必需要留意。我我的认为咱们在服务器端开发的时候,也能够应用这个原则。 idea
由于Android内存受限,减小内存分配,就意味着减小没必要要的垃圾回收,进而能够避免App在使用中出现停顿等现象。 debug
好比说方法的返回值能用基本类型的表示的,就不要用一个java bean来表示;能用一个基本类型的数组表示的,就不要用一个java bean数组来表示。 rest
3. 不要用反射,除非无路可走。
这个对App的性能是一个很是大的损耗。除非是为了App开发中为了OS不用版本的兼容性而使用反射。
4. 使用最小的空间来存储更多的数据
经过学习和使用,Android里面有一种很是高效的数据存储方式:
public void writeToParcel(Parcel dest, int flags) { dest.writeLong(time); int bat = (((int)cmd)&0xff) | ((((int)batteryLevel)<<8)&0xff00) | ((((int)batteryStatus)<<16)&0xf0000) | ((((int)batteryHealth)<<20)&0xf00000) | ((((int)batteryPlugType)<<24)&0xf000000); dest.writeInt(bat); }
Android用一个int存储了5个数据项。这段代码来自于Android 存储电池历史文件源代码。这段代码给我了不少的启示。当咱们想把一些数据存储在文件中,就能够用这种方式:紧凑,快速。
最后一个是选择了一个新的IDE: Android Studio和Intellij Idea。用了新的IDE以后,开发效率确实提升了不很多,并且心情也愉悦了不少。