本人从事java服务器端开发已经有6,7年了,最近这一年多转去做Android开发。到今天觉得应该把自己的一些感受写下来,供以后参考。
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:
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. 尽量少的创建临时对象,尽量使用基本类型
在服务器端开发的时候,我们很少会注意这个问题。但是在Android开发中,这些就是我们必须要留意。我个人认为我们在服务器端开发的时候,也可以应用这个原则。
因为Android内存受限,减少内存分配,就意味着减少不必要的垃圾回收,进而可以避免App在使用中出现停顿等现象。
比如说方法的返回值能用基本类型的表示的,就不要用一个java bean来表示;能用一个基本类型的数组表示的,就不要用一个java bean数组来表示。
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之后,开发效率确实提高了不不少,而且心情也愉悦了很多。