J2ME中有关性能设计

03-02-25 banq

J2ME由于运行的资源有限,有关性能的考量更重要,当然这些考量有的也适合在一般java编程中:

Performance-Driven Programming

When developing applications for mobile devices with a small footprint, it is crucial to make your applications run faster. The less time your application takes to run, the happier your customers are going to be. Here are some guidelines to help you optimize performance:

1.Do not initialize objects to null. That chore is handled automatically.

无须初始化object为null 这些自动做了。

2.Wherever possible, use local variables instead of class members. Access is quicker.

尽可能使用本地变量代替类成员,这样访问速度快

3.Minimize method calls. The Java Virtual Machine[tm] (JVM[tm]) loads and stores a stack frame every time it calls a method. For example, instead of doing something like this...

减少方法的调用,不用使用下列方式:

for(int i=0;i<obj.length; i++) {

// do something with array elements

}

...where the length of the array is evaluated every time the loop iterates, it is more efficient to define a local variable and call the accessor only once:

应该使用下面方式,这样就不会在每次循环时创建obj的长度:

int len = obj.length;

for(int i=0; i<len; i++) {

// do something with array elements

}

4.Minimize object creation.

减少对象的创建。对象创建需要对象销毁,因此耗费性能,最好能重新利用对象。

Object creation leads to object destruction and reduces performance. Instead, design objects that can be recycled. Instead of creating return objects inside of methods, consider passing a reference to the return object and modifying its values. For example, this code snippet...

int len = record.length;

try {

for(int i=0; i<len; i++) {

MyObject obj = new MyObject();

// do something with obj

}

} catch(Exception e) {

e.printStackTrace();

}

... creates and destroys a new instance of MyObject every time the loop iterates. You can avoid this object churning -- continually creating and discarding objects in the memory heap -- by moving the object creation outside the loop. A more efficient way to rewrite the code above would be to create the object outside the try statement and reuse that object as follows:

int len = record.length;

MyObject obj = new MyObject();

try {

for(int i=0; i<len; i++) {

// do something with obj

}

} catch(Exception e) {

e.printStackTrace();

}

By reusing a single object instead of creating many the program uses less memory and the processor doesn't spend as much time collecting garbage.

5.Avoid string concatenation. Concatenating objects with the + operator causes object creation and subsequent garbage collection, and thus chews up both memory and processor time. It is more efficient to use StringBuffer.

Avoid synchronization. If a method takes longer than a fraction of a second to run, consider placing the call to it in a separate thread.

tomjava
2003-03-02 15:19

banq大哥最近也在研究J2ME吗?

banq
2003-03-03 14:47

我主要在研究J2ME的服务器端,当然也需要对J2ME有一个了解。

前台J2ME+后台J2EE是一个趋势。