Java性能调优

释放双眼,带上耳机,听听看~!

http://www.uml.org.cn/j2ee/201509234.asp?artid=17016

 

    分享到 捐助     分享到 捐助     分享到 捐助
    分享到 捐助     分享到 捐助
    分享到 捐助
Java性能调优
 
作者:傲慢的上校 来源:CSDN 发布于 2015-9-23
来自于要资料    28 次浏览     评价: 好 中 差       来自于要资料    28 次浏览     评价: 好 中 差      
来自于要资料    28 次浏览     评价: 好 中 差      
 
写Java也有n年了,现在还是有不少的坏的代码习惯,也通过学习别人的代码学到了不少好的习惯。这篇文章主要是整理的资料。留给自己做个警戒,提示以后写代码的时候注意!在文章的后面,会提供整理的原材料下载。 一、类和对象使用技巧 1、尽量少用new生成新对象 用new创建类的实例时,构造雨数链中所有构造函数都会被自动调用,操作速度较慢。在某些时候可复用现有对象。比如在进行大量St rillg操作时,可用StringBuffer娄代替String类,以避免生成大量的对象。用 new关键词创建类的实例时,构造函数链中的所有构造函数都会被自动调用。但如果一个对象实现了 Cloneable 接口,我们可以调用她的 clone() 方法。clone()方法不会调用任何类构造函数。 下面是 Factory 模式的一个典型实现。 public static Credit getNewCredit()
{
return new Credit();
} 改进后的代码使用 clone() 方法, private static Credit BaseCredit = new Credit();
public static Credit getNewCredit()
{

1
2
1return (Credit)BaseCredit.clone();  
2

} 2、使用clone()方法生成新对象 如果一个对象实现Cloneable接口,就可以调用它的clone()方法。clone()方法不会泪用任何类构造函数,比使用new方法创建实例速度要快。 3、尽量使用局部变量(栈变量) 调用方法时传递的参数及调用中创建的临时变量保存在栈(Stack)中,速度较快。其他变量,如静态变量、实例变量都在堆(HeaP)中创建,速度较慢。访问静态变量和实例变量将会比访问局部变量多耗费 2-3 个时钟周期。如果一个变量需要经常访问,那么你就需要考虑这个变量的作用域了。static? local?还是实例变量? 调用方法时传递的参数以及在调用中创建的临时变量都保存在栈(Stack)中,速度较快。其他变量,如静态变量,实例变量等,都在堆(Heap)中创建,速度较慢。 例子: public class usv {
void getsum (int[] values) {
for (int i=0; i < value.length; i++) {
_sum += value[i]; // violation.
}
}
void getsum2 (int[] values) {
for (int i=0; i < value.length; i++) {
_staticsum += value[i];
}
}
private int _sum;
private static int _staticsum;
} 更正:如果可能,请使用局部变量作为你经常访问的变量。 你可以按下面的方法来修改 getsum()方法: void getsum (int[] values) {
int sum = _sum; // temporary local variable.
for (int i=0; i < value.length; i++) {
sum += value[i];
}
_sum = sum; 4、减少方法调用 面向对象设计的一个基本准则是通过方法间接访问对象的属性,但方法调用会占用·些开销访问。可以避免在同一个类中通过训州函数或方法(get或set)来设置或调用该对象的灾例变量,这比直接访问变量要慢。为了减少方法调用,可以将方法中的代码复制到调用方法的地方,比如大量的循环中,这样可以节省方法调用的开销。但带来性能提升的同时会牺牲代码的可读性,可根据实际需要平衡两者关系。 5、使用final类和final、static、private方法 带有final修饰符的类是不可派生的。如果指定一个类为finaI,则该类所有的方法都是final。JAVA编障器会寻找机会内联(inIine)所有的final方法。此举能够提升程序性能。使用final、static、private的方法是不能被覆盖的,JAVA不需要在稃序运行的时候动态关联实现方法,从而节省了运行时间。 带有 final 修饰符的类是不可派生的。在 JAVA核心 API中,有许多应用 final 的例子,例如 java.lang.String。为 String 类指定 final 防止了使用者覆盖 length()方法。另外,如果一个类是 final 的,则该类所有方法都是 final 的。java 编译器会寻找机会内联(inline)所有的final 方法(这和具体的编译器实现有关)。此举能够使性能平均提高 50%。 6、让访问实例内变量的 getter/setter 方法变成”final” 简单的 getter/setter 方法应该被置成 final,这会告诉编译器,这个方法不会被重载,所以,可以变成”inlined” 例子: class maf {
public void setsize (int size) {
_size = size;
}
private int _size;
} 更正: class daf_fixed {
final public void setsize (int size) {
_size = size;
}
private int _size;
} 7、避免不需要的 instanceof 操作 如果左边的对象的静态类型等于右边的,instanceof 表达式返回永远为 true。 例子: public class uiso {
public uiso () {}
}
class dog extends uiso {
void method (dog dog, uiso u) {
dog d = dog;
if (d instanceof uiso) // always true.
system.out.println("dog is a uiso");
uiso uiso = u;
if (uiso instanceof object) // always true.
system.out.println("uiso is an object");
}
} 更正:删掉不需要的 instanceof 操作。 class dog extends uiso {
void method () {
dog d;
system.out.println ("dog is an uiso");
system.out.println ("uiso is an uiso");
}
} 8、避免不需要的造型操作 所有的类都是直接或者间接继承自 object。同样,所有的子类也都隐含的“等于”其父类。那么,由子类造型至父类的操作就是不必要的了。  例子: class unc {
string _id = "unc";
}
class dog extends unc {
void method () {
dog dog = new dog ();
unc animal = (unc)dog; // not necessary.
object o = (object)dog; // not necessary.
}
} 更正: class dog extends unc {
void method () {
dog dog = new dog();
unc animal = dog;
object o = dog;
}
} 9.尽量重用对象。 特别是 String 对象的使用中,出现字符串连接情况时应使用 StringBuffer 代替,由于系统不仅要花时间生成对象,以后可能还需要花时间对这些对象进行垃圾回收和处理。因此生成过多的对象将会给程序的性能带来很大的影响。 10、不要重复初始化变量。 默认情况下,调用类的构造函数时,java 会把变量初始化成确定的值,所有的对象被设置成null,整数变量设置成 0,float 和 double 变量设置成 0.0,逻辑值设置成 false。当一个类从另一个类派生时,这一点尤其应该注意,因为用 new 关键字创建一个对象时,构造函数链中的所有构造函数都会被自动调用。 这里有个注意,给成员变量设置初始值但需要调用其他方法的时候,最好放在一个方法比如initXXX()中,因为直接调用某方法赋值可能会因为类尚未初始化而抛空指针异常,public int state = this.getState(); 11、不要过分创建对象 过分的创建对象会消耗系统的大量内存,严重时,会导致内存泄漏,因此,保证过期的对象的及时回收具有重要意义。 JVM 的 GC并非十分智能,因此建议在对象使用完毕后,手动设置成 null。 二、Java I/O技巧 I/O性能常常是应用程序性能瓶颈,优化I/O性能就显得极为系要。在进行I/0操作时,匿遵循以下原则:尽可能少的访问磁盘;尽可能少的I方问底层的操作系统;尽可能少的方法调用;尽可能少处理个别的处理字节和字符。基于以上原则,可以通过以下技巧提高I/O速度: 1、使州缓冲提高I/O性能。 常用的实现方法有以下2种:使用用于字符的BufferedReader和用于宁节的BufferedlnputStream类,或者使用块读取方法次读取一大块数据。 2、lnputStream比Reader高效,OutputStream比Writer高效。 当使用Unicode字符串时,Write类的开销比较大。因为它要实Uoicode到字节(byte)的转换。因此,如果可能的话,在使用 Write类之前就实现转换或用OutputStream类代替Writer娄来使用。 3、在适当的时候用byte替代char。 1个char用2个字节保存字符,而byte只需要1个,因此用byte保存字符消耗的内存和需要执行的机器指令更少。更重要的是,用byte避免了进行Unicode转换。因此,如果町能的话,应尽量使用byte替代char。 4、有缓冲的块操作10要比缓冲的流字符IO快。 对于字符IO,虽然缓冲流避免了每次读取字符时的系统调用开销,但仍需要一次或多次方法调用。带缓冲的块10比缓冲流IO快2到4倍,比无缓冲的IO快4到40倍。 5、序列化时,使用原子类型。 当序列化一个类或对象时,对干那些原子类型(atomic)或可以重建的元素,要标识为transient类型,这样就不用每一次都进行序列化。如果这砦序列化的对象要在网络上传输,这一小小的改变对性能会有很大的提高。 6、在finally 块中关闭stream 程序中使用到的资源应当被释放,以避免资源泄漏。这最好在 finally 块中去做。不管程序执行的结果如何,finally 块总是会执行的,以确保资源的正确关闭。 例子: import java.io.*;
public class cs {
public static void main (string args[]) {
cs cs = new cs ();
cs.method ();
}
public void method () {
try {
fileinputstream fis = new fileinputstream ("cs.java");
int count = 0;
while (fis.read () != -1)
count++;
system.out.println (count);
fis.close ();
} catch (filenotfoundexception e1) {
} catch (ioexception e2) {
}
}
} 更正: 在最后一个 catch 后添加一个 finally 块 7、SQL语句 在 java+Oracle 的应用系统开发中,java 中内嵌的 SQL 语言应尽量使用大写形式,以减少Oracle 解析器的解析负担。 8、尽早释放资源 java 编程过程中,进行数据库连接,I/O 流操作,在使用完毕后,及时关闭以释放资源。因为对这些大对象的操作会造成系统大的开销。 三、异常(Exceptions)使用技巧 JAVA语言中提供了try/catch来开发方便用户捕捉异常,进行异常的处理。但是如果使用不当,也会给JAvA程序的性能带来影响。因此,要注意以下儿点。慎用异常,异常对性能不利。抛出异常首先要创建一个新的对象。Throwable接口的构造函数调用名为fillInStackTrace()的本地(Native)方法filllnStackTrace()方法检查堆栈,收集调用跟踪信息。只要有异常被抛出,VM就必须调整调用堆栈。 1、避免使用异常来控制程序流程 如果可以用if、while等逻辑语句来处理,那么就尽可能的不用try/catch语句。抛出异常首先要创建一个新的对象。Throwable 接口的构造函数调用名为 fillInStackTrace()的本地方法,fillInStackTrace()方法检查栈,收集调用跟踪信息。只要有异常被抛出,VM 就必须调整调用栈,因为在处理过程中创建了一个新的对象。 异常只能用于错误处理,不应该用来控制程序流程。 2、尽可能重用异常 在必须要进行异常的处理时,要尽可能的重用已经存在的异常对象。因为在异常的处理中,生成个异常对象要消耗掉大部分的时间。 3、将try/catch 块移出循环 把try/catch块放入循环体内,会极大的影响性能,如果编译 jit 被关闭或者你所使用的是一个不带 jit 的jvm,性能会将下降21%之多! 例子: import java.io.fileinputstream;
public class try {
void method (fileinputstream fis) {
for (int i = 0; i < size; i++) {
try { // violation
_sum += fis.read();
} catch (exception e) {}
}
}
private int _sum;
} 更正:将 try/catch块移出循环 void method (fileinputstream fis) {
try {
for (int i = 0; i < size; i++) { sum += fis.read();
}
} catch (exception e) {}
} 四、线程使用技巧 1、在使用大量线程(Threading)的场合使用线程池管理 生成和启动新线程是个相对较慢的过程,生成人量新线程会严重影响应J
}j程序性能。通过使用线程池,由线程池管理器(thread pool manager)来生成新线程或分配现有线程,柏省生成线程的叫间。 2、防止过多的同步 不必要的同步常常会造成程序性能的下降,调用同步方法比调用非同步方法要花费更多的时间。如果程序是单线程,则没有必要使用同步。 3、同步方法而不要同步整个代码段 对某个方法或函数进行同步比对整个代码段进行同步的性能要好。 4、在追求速度的场合,用ArrayList和HashMap代替Vector和Hashtable Vector和Hashtable实现了同步以提高线程安全性,但速度较没有实现同步的ArrayList和Ha shMap要慢,可以根据需要选择使用的类。 5、使用notify()而不是notifyAll() 使用哪个方法要取决于程序的没计,但应尽可能使用notify(),因为notify()只唤醒等待指定对象的线程,比唤醒所有等待线稃的notifyAll0速度更快。 6、不要在循环中调用 synchronized(同步)方法 方法的同步需要消耗相当大的资料,在一个循环中调用它绝对不是一个好主意。 例子: import java.util.vector;
public class syn {
public synchronized void method (object o) {
}
private void test () {
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i)); // violation
}
}
private vector vector = new vector (5, 5);
} 更正:不要在循环体中调用同步方法,如果必须同步的话,推荐以下方式: import java.util.vector;
public class syn {
public void method (object o) {
}
private void test () {
synchronized{//在一个同步块中执行非同步方法
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i));
}
}
}
private vector vector = new vector (5, 5);
} 7、单线程应尽量使用 HashMap, ArrayList。 除非必要,否则不推荐使用 HashTable,Vector,她们使用了同步机制,而降低了性能。 五、其它常用技巧 1、使用移位操作替代乘除法操作可以极大地提高性能 "/"是一个很“昂贵”的操作,使用移位操作将会更快更有效。 例子: public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a / 4; // should be replaced with "a >> 2".
int div2 = a / 8; // should be replaced with "a >> 3".
int temp = a / 3;
int mul = a * 4; // should be replaced with "a << 2".
int mul2 = 8 * a; // should be replaced with "a << 3".
int temp2 = a * 3;
}
} 更正: public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a >> 2;
int div2 = a >> 3;
int temp = a / 3; // 不能转换成位移操作
int mul = a << 2;
int mul2 = a << 3;
int temp = a * 3; // 不能转换
}
} PS:除非是在一个非常大的循环内,性能非常重要,而且你很清楚你自己在做什么,方可使用这种方法。否则提高性能所带来的程序晚读性的降低将是不合算的。 2、对Vector中最后位置的添加、删除操作要远远快于埘第一个元素的添加、删除操作 3、当复制数组时,使用System.arraycop()方法 例子: public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
for (int i = 0; i < array2.length; i++) {
array2 [i] = array1 [i]; // violation
}
}
} 更正: public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
system.arraycopy(array1, 0, array2, 0, 100);
}
} 4、使用复合赋值运算符 a=a+b和a+b住编译时会产生不同JAVA字奇码,后者回快于前者。冈此,使用+=、-=、+=、/=等复台赋值运算符会使运算速度稍有提升。 5、用int而不用其它基本类型 对int类犁的操作通常比其它基本类型要快,因此尽量使用int类型。 6、在进行数据库连接和网络连接时使用连接池 这类连接往往会耗费大量时间,应尽量避免。可以使用连接池技术,复用现有连接。 7、用压缩加快网络传输速度一种常用方法是把相关文件打包到一个jar文件中。 用一个Jar文件发送多个文件还叫以避免每个文件打开和关闭网络连接所造成的开销。 8、在数据库应用程序中使用批处理功能 可以利用Statement类的addBatch()氟l exexuteBatch法成批地提交sql语句,以节省网络传输开销。在执行大量相似语句时,可以使用PreParedState—类,它可以一次性编译语句并多次执行,用参数最后执行的sql语句。 9、消除循环体中不必要的代码 这似乎是每个程序员都知道的基本原则,没有必出,但很多人往往忽略一些细节。如下列代码: Vector aVector= …;
for(int i=0;i<aVector size();i++)(
System out printlll(aVector elementAt(i)toStringO);
} 这段代码中没循环一次就要调用aVector.size()方法,aVector的长度不变的话,可以改为一下代码: Vector aVector= …:
int length=aVector size();
for(int i=0;i<length;i++)f
System out println(aVector elememAt(i)toStringO);
) 这样消除了每次调用aVector.size()方法的开销。 10、为'vectors' 和 'hashtables'定义初始大小 jvm 为 vector 扩充大小的时候需要重新创建一个更大的数组,将原原先数组中的内容复制过来,最后,原先的数组再被回收。可见 vector 容量的扩大是一个颇费时间的事。 通常,默认的 10 个元素大小是不够的。你最好能准确的估计你所需要的最佳大小。 例子: import java.util.vector;
public class dic {
public void addobjects (object[] o) {
// if length > 10, vector needs to expand
for (int i = 0; i< o.length;i++) {
v.add(o); // capacity before it can add more elements.
}
}
public vector v = new vector(); // no initialcapacity.
} <span style="WHITE-SPACE: pre"> </span><span style="font-size:14px;">更正: 自己设定初始大小。 </span> public vector v = new vector(20);
public hashtable hash = new hashtable(10); 11、如果只是查找单个字符的话,用charat()代替startswith() 用一个字符作为参数调用 startswith()也会工作的很好,但从性能角度上来看,调用用 string api 无疑是错误的! 例子: public class pcts {
private void method(string s) {
if (s.startswith("a")) { // violation
// …
}
}
} 更正 :将'startswith()' 替换成'charat()'. public class pcts {
private void method(string s) {
if ('a' == s.charat(0)) {
// …
}
}
} 12、在字符串相加的时候,使用 ' ' 代替 " ",如果该字符串只有一个字符的话 例子: public class str {
public void method(string s) {
string string = s + "d" // violation.
string = "abc" + "d" // violation.
}
} 更正: 将一个字符的字符串替换成' ' public class str {
public void method(string s) {
string string = s + 'd'
string = "abc" + 'd'
}
} 13、对于 boolean 值,避免不必要的等式判断 将一个 boolean 值与一个 true 比较是一个恒等操作(直接返回该 boolean 变量的值). 移走对于boolean 的不必要操作至少会带来 2 个好处: 1)代码执行的更快 (生成的字节码少了 5 个字节); 2)代码也会更加干净 。 例子: public class ueq {
boolean method (string string) {
return string.endswith ("a") == true; // violation
}
} 更正: class ueq_fixed {
boolean method (string string) {
return string.endswith ("a");
}
} 14、对于常量字符串,用'string' 代替 'stringbuffer' 常量字符串并不需要动态改变长度。 例子: public class usc {
string method () {
stringbuffer s = new stringbuffer ("hello");
string t = s + "world!";
return t;
}
} 更正: 把 stringbuffer 换成 string,如果确定这个 string 不会再变的话,这将会减少运行开销提高性能。 15、用'stringtokenizer' 代替 'indexof()' 和'substring()' 字符串的分析在很多应用中都是常见的。使用 indexof()和 substring()来分析字符串容易导致 stringindexoutofboundsexception。而使用 stringtokenizer 类来分析字符串则会容易一些,效率也会高一些。 例子: public class ust {
void parsestring(string string) {
int index = 0;
while ((index = string.indexof(".", index)) != -1) {
system.out.println (string.substring(index, string.length()));
}
}
} 16、使用条件操作符替代"if (cond) else " 结构 条件操作符更加的简捷 例子: public class if {
public int method(boolean isdone) {
if (isdone) {
return 0;
} else {
return 10;
}


1
2
3
4
5
6
1 void method2(boolean istrue) {  
2    if (istrue) {  
3        _value = 0;  
4    } else {  
5        _value = 1;  
6

<span style="WHITE-SPACE: pre"> </span>}
}
} 更正: public class if {
public int method(boolean isdone) {
return (isdone ? 0 : 10);
}


1
2
3
1void method(boolean istrue) {  
2&lt;span style=&quot;WHITE-SPACE: pre&quot;&gt; &lt;/span&gt;_value = (istrue ? 0 : 1);       // comp  
3

<span style="WHITE-SPACE: pre"> </span>}
private int _value = 0;

} 17、不要在循环体中实例化变量 在循环体中实例化临时变量将会增加内存消耗 例子: import java.util.vector;
public class loop {
void method (vector v) {
for (int i=0;i < v.size();i++) {
object o = new object();
o = v.elementat(i);
}
}
} 更正: 在循环体外定义变量,并反复使用 import java.util.vector;
public class loop {
void method (vector v) {
object o;
for (int i=0;i<v.size();i++) {
o = v.elementat(i);
}
}
} 18、确定 stringbuffer的容量 stringbuffer 的构造器会创建一个默认大小(通常是 16)的字符数组。在使用中,如果超出这个大小,就会重新分配内存,创建一个更大的数组,并将原先的数组复制过来,再丢弃旧的数组。在大多数情况下,你可以在创建 stringbuffer 的时候指定大小,这样就避免了在容量不够的时候自动增长,以提高性能。 例子: public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(); // violation
buffer.append ("hello");
}
} 更正:为 stringbuffer 提供大小。 public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(max);
buffer.append ("hello");
}
private final int max = 100;
} 19、不要总是使用取反操作符(!) 取反操作符(!)降低程序的可读性,所以不要总是使用。 例子: public class dun {
boolean method (boolean a, boolean b) {
if (!a)
return !a;
else
return !b;
}
} 更正:如果可能不要使用取反操作符(!) 20、与一个接口 进行instanceof 操作 基于接口的设计通常是件好事,因为它允许有不同的实现,而又保持灵活。只要可能,对一个对象进行 instanceof 操作,以判断它是否某一接口要比是否某一个类要快。 例子: public class insof {
private void method (object o) {
if (o instanceof interfacebase) { } // better
if (o instanceof classbase) { } // worse.
}
}

class classbase {}
interface interfacebase {} 21、采用在需要的时候才开始创建的策略。 例如: String str="abc";
if(i==1){ list.add(str);} 应修改为: if(i==1){String str="abc"; list.add(str);} 22、通过 StringBuffer 的构造函数来设定他的初始化容量,可以明显提升性能。 StringBuffer 的默认容量为 16,当 StringBuffer 的容量达到最大容量时,她会将自身容量增加到当前的 2 倍+2,也就是 2n+2。无论何时,只要 StringBuffer 到达她的最大容量,她就不得不创建一个新的对象数组,然后复制旧的对象数组,这会浪费很多时间。所以给StringBuffer 设置一个合理的初始化容量值,是很有必要的! 23、合理使用 java.util.Vector Vector 与 StringBuffer 类似,每次扩展容量时,所有现有元素都要赋值到新的存储空间中。Vector 的默认存储能力为 10个元素,扩容加倍。 vector.add(index,obj) 这个方法可以将元素 obj 插入到index 位置,但 index 以及之后的元素依次都要向下移动一个位置(将其索引加 1)。 除非必要,否则对性能不利。 同样规则适用于 remove(int index)方法,移除此向量中指定位置的元素。将所有后续元素左移(将其索引减 1)。返回此向量中移除的元素。所以删除 vector 最后一个元素要比删除第1 个元素开销低很多。删除所有元素最好用 removeAllElements()方法。 如果要删除 vector 里的一个元素可以使用 vector.remove(obj);而不必自己检索元素位置,再删除,如 int index = indexOf(obj);vector.remove(index); 24、不要将数组声明为:public static final 25、HaspMap 的遍历 Map<String, String[]> paraMap = new HashMap<String, String[]>();
for( Entry<String, String[]> entry : paraMap.entrySet() )
{
String appFieldDefId = entry.getKey();
String[] values = entry.getValue();
} 利用散列值取出相应的 Entry 做比较得到结果,取得 entry的值之后直接取 key和 value。 26、array(数组)和 ArrayList 的使用。 array 数组效率最高,但容量固定,无法动态改变,ArrayList 容量可以动态增长,但牺牲了效率。 27、StringBuffer,StringBuilder 的区别 StringBuffer,StringBuilder 的区别在于:java.lang.StringBuffer 线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。StringBuilder 与该类相比,通常应该优先使用 StringBuilder 类,因为她支持所有相同的操作,但由于她不执行同步,所以速度更快。为了获得更好的性能,在构造 StringBuffer 或 StringBuilder 时应尽量指定她的容量。当然如果不超过 16 个字符时就不用了。 相同情况下,使用 StringBuilder 比使用 StringBuffer 仅能获得 10%~15%的性能提升,但却要冒多线程不安全的风险。综合考虑还是建议使用 StringBuffer。 28、 尽量使用基本数据类型代替对象。 29、用简单的数值计算代替复杂的函数计算,比如查表方式解决三角函数问题。 30、使用具体类比使用接口效率高,但结构弹性降低了,但现代 IDE 都可以解决这个问题。 31、考虑使用静态方法 如果你没有必要去访问对象的外部,那么就使你的方法成为静态方法。她会被更快地调用,因为她不需要一个虚拟函数导向表。这同事也是一个很好的实践,因为她告诉你如何区分方法的性质,调用这个方法不会改变对象的状态。 32.应尽可能避免使用内在的GET,SET 方法 android 编程中,虚方法的调用会产生很多代价,比实例属性查询的代价还要多。我们应该在外包调用的时候才使用 get,set方法,但在内部调用的时候,应该直接调用。 33、避免枚举,浮点数的使用。 34、二维数组比一维数组占用更多的内存空间,大概是 10 倍计算。 35、SQLite SQLite 数据库读取整张表的全部数据很快,但有条件的查询就要耗时 30-50MS,大家做这方面的时候要注意,尽量少用,尤其是嵌套查找! 36、奇偶判断 不要使用 i % 2 == 1 来判断是否是奇数,因为 i为负奇数时不成立,请使用 i % 2 != 0 来判断是否是奇数,或使用 高效式 (i & 1) != 0 来判断。 |写Java也有n年了,现在还是有不少的坏的代码习惯,也通过学习别人的代码学到了不少好的习惯。这篇文章主要是整理的资料。留给自己做个警戒,提示以后写代码的时候注意!在文章的后面,会提供整理的原材料下载。 一、类和对象使用技巧 1、尽量少用new生成新对象 用new创建类的实例时,构造雨数链中所有构造函数都会被自动调用,操作速度较慢。在某些时候可复用现有对象。比如在进行大量St rillg操作时,可用StringBuffer娄代替String类,以避免生成大量的对象。用 new关键词创建类的实例时,构造函数链中的所有构造函数都会被自动调用。但如果一个对象实现了 Cloneable 接口,我们可以调用她的 clone() 方法。clone()方法不会调用任何类构造函数。 下面是 Factory 模式的一个典型实现。 public static Credit getNewCredit()
{
return new Credit();
} 改进后的代码使用 clone() 方法, private static Credit BaseCredit = new Credit();
public static Credit getNewCredit()
{
return (Credit)BaseCredit.clone();
} 2、使用clone()方法生成新对象 如果一个对象实现Cloneable接口,就可以调用它的clone()方法。clone()方法不会泪用任何类构造函数,比使用new方法创建实例速度要快。 3、尽量使用局部变量(栈变量) 调用方法时传递的参数及调用中创建的临时变量保存在栈(Stack)中,速度较快。其他变量,如静态变量、实例变量都在堆(HeaP)中创建,速度较慢。访问静态变量和实例变量将会比访问局部变量多耗费 2-3 个时钟周期。如果一个变量需要经常访问,那么你就需要考虑这个变量的作用域了。static? local?还是实例变量? 调用方法时传递的参数以及在调用中创建的临时变量都保存在栈(Stack)中,速度较快。其他变量,如静态变量,实例变量等,都在堆(Heap)中创建,速度较慢。 例子: public class usv {
void getsum (int[] values) {
for (int i=0; i < value.length; i++) {
_sum += value[i]; // violation.
}
}
void getsum2 (int[] values) {
for (int i=0; i < value.length; i++) {
_staticsum += value[i];
}
}
private int _sum;
private static int _staticsum;
} 更正:如果可能,请使用局部变量作为你经常访问的变量。 你可以按下面的方法来修改 getsum()方法: void getsum (int[] values) {
int sum = _sum; // temporary local variable.
for (int i=0; i < value.length; i++) {
sum += value[i];
}
_sum = sum; 4、减少方法调用 面向对象设计的一个基本准则是通过方法间接访问对象的属性,但方法调用会占用·些开销访问。可以避免在同一个类中通过训州函数或方法(get或set)来设置或调用该对象的灾例变量,这比直接访问变量要慢。为了减少方法调用,可以将方法中的代码复制到调用方法的地方,比如大量的循环中,这样可以节省方法调用的开销。但带来性能提升的同时会牺牲代码的可读性,可根据实际需要平衡两者关系。 5、使用final类和final、static、private方法 带有final修饰符的类是不可派生的。如果指定一个类为finaI,则该类所有的方法都是final。JAVA编障器会寻找机会内联(inIine)所有的final方法。此举能够提升程序性能。使用final、static、private的方法是不能被覆盖的,JAVA不需要在稃序运行的时候动态关联实现方法,从而节省了运行时间。 带有 final 修饰符的类是不可派生的。在 JAVA核心 API中,有许多应用 final 的例子,例如 java.lang.String。为 String 类指定 final 防止了使用者覆盖 length()方法。另外,如果一个类是 final 的,则该类所有方法都是 final 的。java 编译器会寻找机会内联(inline)所有的final 方法(这和具体的编译器实现有关)。此举能够使性能平均提高 50%。 6、让访问实例内变量的 getter/setter 方法变成”final” 简单的 getter/setter 方法应该被置成 final,这会告诉编译器,这个方法不会被重载,所以,可以变成”inlined” 例子: class maf {
public void setsize (int size) {
_size = size;
}
private int _size;
} 更正: class daf_fixed {
final public void setsize (int size) {
_size = size;
}
private int _size;
} 7、避免不需要的 instanceof 操作 如果左边的对象的静态类型等于右边的,instanceof 表达式返回永远为 true。 例子: public class uiso {
public uiso () {}
}
class dog extends uiso {
void method (dog dog, uiso u) {
dog d = dog;
if (d instanceof uiso) // always true.
system.out.println("dog is a uiso");
uiso uiso = u;
if (uiso instanceof object) // always true.
system.out.println("uiso is an object");
}
} 更正:删掉不需要的 instanceof 操作。 class dog extends uiso {
void method () {
dog d;
system.out.println ("dog is an uiso");
system.out.println ("uiso is an uiso");
}
} 8、避免不需要的造型操作 所有的类都是直接或者间接继承自 object。同样,所有的子类也都隐含的“等于”其父类。那么,由子类造型至父类的操作就是不必要的了。  例子: class unc {
string _id = "unc";
}
class dog extends unc {
void method () {
dog dog = new dog ();
unc animal = (unc)dog; // not necessary.
object o = (object)dog; // not necessary.
}
} 更正: class dog extends unc {
void method () {
dog dog = new dog();
unc animal = dog;
object o = dog;
}
} 9.尽量重用对象。 特别是 String 对象的使用中,出现字符串连接情况时应使用 StringBuffer 代替,由于系统不仅要花时间生成对象,以后可能还需要花时间对这些对象进行垃圾回收和处理。因此生成过多的对象将会给程序的性能带来很大的影响。 10、不要重复初始化变量。 默认情况下,调用类的构造函数时,java 会把变量初始化成确定的值,所有的对象被设置成null,整数变量设置成 0,float 和 double 变量设置成 0.0,逻辑值设置成 false。当一个类从另一个类派生时,这一点尤其应该注意,因为用 new 关键字创建一个对象时,构造函数链中的所有构造函数都会被自动调用。 这里有个注意,给成员变量设置初始值但需要调用其他方法的时候,最好放在一个方法比如initXXX()中,因为直接调用某方法赋值可能会因为类尚未初始化而抛空指针异常,public int state = this.getState(); 11、不要过分创建对象 过分的创建对象会消耗系统的大量内存,严重时,会导致内存泄漏,因此,保证过期的对象的及时回收具有重要意义。 JVM 的 GC并非十分智能,因此建议在对象使用完毕后,手动设置成 null。 二、Java I/O技巧 I/O性能常常是应用程序性能瓶颈,优化I/O性能就显得极为系要。在进行I/0操作时,匿遵循以下原则:尽可能少的访问磁盘;尽可能少的I方问底层的操作系统;尽可能少的方法调用;尽可能少处理个别的处理字节和字符。基于以上原则,可以通过以下技巧提高I/O速度: 1、使州缓冲提高I/O性能。 常用的实现方法有以下2种:使用用于字符的BufferedReader和用于宁节的BufferedlnputStream类,或者使用块读取方法次读取一大块数据。 2、lnputStream比Reader高效,OutputStream比Writer高效。 当使用Unicode字符串时,Write类的开销比较大。因为它要实Uoicode到字节(byte)的转换。因此,如果可能的话,在使用 Write类之前就实现转换或用OutputStream类代替Writer娄来使用。 3、在适当的时候用byte替代char。 1个char用2个字节保存字符,而byte只需要1个,因此用byte保存字符消耗的内存和需要执行的机器指令更少。更重要的是,用byte避免了进行Unicode转换。因此,如果町能的话,应尽量使用byte替代char。 4、有缓冲的块操作10要比缓冲的流字符IO快。 对于字符IO,虽然缓冲流避免了每次读取字符时的系统调用开销,但仍需要一次或多次方法调用。带缓冲的块10比缓冲流IO快2到4倍,比无缓冲的IO快4到40倍。 5、序列化时,使用原子类型。 当序列化一个类或对象时,对干那些原子类型(atomic)或可以重建的元素,要标识为transient类型,这样就不用每一次都进行序列化。如果这砦序列化的对象要在网络上传输,这一小小的改变对性能会有很大的提高。 6、在finally 块中关闭stream 程序中使用到的资源应当被释放,以避免资源泄漏。这最好在 finally 块中去做。不管程序执行的结果如何,finally 块总是会执行的,以确保资源的正确关闭。 例子: import java.io.
;
public class cs {
public static void main (string args[]) {
cs cs = new cs ();
cs.method ();
}
public void method () {
try {
fileinputstream fis = new fileinputstream ("cs.java");
int count = 0;
while (fis.read () != -1)
count++;
system.out.println (count);
fis.close ();
} catch (filenotfoundexception e1) {
} catch (ioexception e2) {
}
}
} 更正: 在最后一个 catch 后添加一个 finally 块 7、SQL语句 在 java+Oracle 的应用系统开发中,java 中内嵌的 SQL 语言应尽量使用大写形式,以减少Oracle 解析器的解析负担。 8、尽早释放资源 java 编程过程中,进行数据库连接,I/O 流操作,在使用完毕后,及时关闭以释放资源。因为对这些大对象的操作会造成系统大的开销。 三、异常(Exceptions)使用技巧 JAVA语言中提供了try/catch来开发方便用户捕捉异常,进行异常的处理。但是如果使用不当,也会给JAvA程序的性能带来影响。因此,要注意以下儿点。慎用异常,异常对性能不利。抛出异常首先要创建一个新的对象。Throwable接口的构造函数调用名为fillInStackTrace()的本地(Native)方法filllnStackTrace()方法检查堆栈,收集调用跟踪信息。只要有异常被抛出,VM就必须调整调用堆栈。 1、避免使用异常来控制程序流程 如果可以用if、while等逻辑语句来处理,那么就尽可能的不用try/catch语句。抛出异常首先要创建一个新的对象。Throwable 接口的构造函数调用名为 fillInStackTrace()的本地方法,fillInStackTrace()方法检查栈,收集调用跟踪信息。只要有异常被抛出,VM 就必须调整调用栈,因为在处理过程中创建了一个新的对象。 异常只能用于错误处理,不应该用来控制程序流程。 2、尽可能重用异常 在必须要进行异常的处理时,要尽可能的重用已经存在的异常对象。因为在异常的处理中,生成个异常对象要消耗掉大部分的时间。 3、将try/catch 块移出循环 把try/catch块放入循环体内,会极大的影响性能,如果编译 jit 被关闭或者你所使用的是一个不带 jit 的jvm,性能会将下降21%之多! 例子: import java.io.fileinputstream;
public class try {
void method (fileinputstream fis) {
for (int i = 0; i < size; i++) {
try { // violation
_sum += fis.read();
} catch (exception e) {}
}
}
private int _sum;
} 更正:将 try/catch块移出循环 void method (fileinputstream fis) {
try {
for (int i = 0; i < size; i++) { sum += fis.read();
}
} catch (exception e) {}
} 四、线程使用技巧 1、在使用大量线程(Threading)的场合使用线程池管理 生成和启动新线程是个相对较慢的过程,生成人量新线程会严重影响应J
}j程序性能。通过使用线程池,由线程池管理器(thread pool manager)来生成新线程或分配现有线程,柏省生成线程的叫间。 2、防止过多的同步 不必要的同步常常会造成程序性能的下降,调用同步方法比调用非同步方法要花费更多的时间。如果程序是单线程,则没有必要使用同步。 3、同步方法而不要同步整个代码段 对某个方法或函数进行同步比对整个代码段进行同步的性能要好。 4、在追求速度的场合,用ArrayList和HashMap代替Vector和Hashtable Vector和Hashtable实现了同步以提高线程安全性,但速度较没有实现同步的ArrayList和Ha shMap要慢,可以根据需要选择使用的类。 5、使用notify()而不是notifyAll() 使用哪个方法要取决于程序的没计,但应尽可能使用notify(),因为notify()只唤醒等待指定对象的线程,比唤醒所有等待线稃的notifyAll0速度更快。 6、不要在循环中调用 synchronized(同步)方法 方法的同步需要消耗相当大的资料,在一个循环中调用它绝对不是一个好主意。 例子: import java.util.vector;
public class syn {
public synchronized void method (object o) {
}
private void test () {
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i)); // violation
}
}
private vector vector = new vector (5, 5);
} 更正:不要在循环体中调用同步方法,如果必须同步的话,推荐以下方式: import java.util.vector;
public class syn {
public void method (object o) {
}
private void test () {
synchronized{//在一个同步块中执行非同步方法
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i));
}
}
}
private vector vector = new vector (5, 5);
} 7、单线程应尽量使用 HashMap, ArrayList。 除非必要,否则不推荐使用 HashTable,Vector,她们使用了同步机制,而降低了性能。 五、其它常用技巧 1、使用移位操作替代乘除法操作可以极大地提高性能 "/"是一个很“昂贵”的操作,使用移位操作将会更快更有效。 例子: public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a / 4; // should be replaced with "a >> 2".
int div2 = a / 8; // should be replaced with "a >> 3".
int temp = a / 3;
int mul = a * 4; // should be replaced with "a << 2".
int mul2 = 8 * a; // should be replaced with "a << 3".
int temp2 = a * 3;
}
} 更正: public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a >> 2;
int div2 = a >> 3;
int temp = a / 3; // 不能转换成位移操作
int mul = a << 2;
int mul2 = a << 3;
int temp = a * 3; // 不能转换
}
} PS:除非是在一个非常大的循环内,性能非常重要,而且你很清楚你自己在做什么,方可使用这种方法。否则提高性能所带来的程序晚读性的降低将是不合算的。 2、对Vector中最后位置的添加、删除操作要远远快于埘第一个元素的添加、删除操作 3、当复制数组时,使用System.arraycop()方法 例子: public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
for (int i = 0; i < array2.length; i++) {
array2 [i] = array1 [i]; // violation
}
}
} 更正: public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
system.arraycopy(array1, 0, array2, 0, 100);
}
} 4、使用复合赋值运算符 a=a+b和a+b住编译时会产生不同JAVA字奇码,后者回快于前者。冈此,使用+=、-=、+=、/=等复台赋值运算符会使运算速度稍有提升。 5、用int而不用其它基本类型 对int类犁的操作通常比其它基本类型要快,因此尽量使用int类型。 6、在进行数据库连接和网络连接时使用连接池 这类连接往往会耗费大量时间,应尽量避免。可以使用连接池技术,复用现有连接。 7、用压缩加快网络传输速度一种常用方法是把相关文件打包到一个jar文件中。 用一个Jar文件发送多个文件还叫以避免每个文件打开和关闭网络连接所造成的开销。 8、在数据库应用程序中使用批处理功能 可以利用Statement类的addBatch()氟l exexuteBatch法成批地提交sql语句,以节省网络传输开销。在执行大量相似语句时,可以使用PreParedState—类,它可以一次性编译语句并多次执行,用参数最后执行的sql语句。 9、消除循环体中不必要的代码 这似乎是每个程序员都知道的基本原则,没有必出,但很多人往往忽略一些细节。如下列代码: Vector aVector= …;
for(int i=0;i<aVector size();i++)(
System out printlll(aVector elementAt(i)toStringO);
} 这段代码中没循环一次就要调用aVector.size()方法,aVector的长度不变的话,可以改为一下代码: Vector aVector= …:
int length=aVector size();
for(int i=0;i<length;i++)f
System out println(aVector elememAt(i)toStringO);
) 这样消除了每次调用aVector.size()方法的开销。 10、为'vectors' 和 'hashtables'定义初始大小 jvm 为 vector 扩充大小的时候需要重新创建一个更大的数组,将原原先数组中的内容复制过来,最后,原先的数组再被回收。可见 vector 容量的扩大是一个颇费时间的事。 通常,默认的 10 个元素大小是不够的。你最好能准确的估计你所需要的最佳大小。 例子: import java.util.vector;
public class dic {
public void addobjects (object[] o) {
// if length > 10, vector needs to expand
for (int i = 0; i< o.length;i++) {
v.add(o); // capacity before it can add more elements.
}
}
public vector v = new vector(); // no initialcapacity.
} <span style="WHITE-SPACE: pre"> </span><span style="font-size:14px;">更正: 自己设定初始大小。 </span> public vector v = new vector(20);
public hashtable hash = new hashtable(10); 11、如果只是查找单个字符的话,用charat()代替startswith() 用一个字符作为参数调用 startswith()也会工作的很好,但从性能角度上来看,调用用 string api 无疑是错误的! 例子: public class pcts {
private void method(string s) {
if (s.startswith("a")) { // violation
// …
}
}
} 更正 :将'startswith()' 替换成'charat()'. public class pcts {
private void method(string s) {
if ('a' == s.charat(0)) {
// …
}
}
} 12、在字符串相加的时候,使用 ' ' 代替 " ",如果该字符串只有一个字符的话 例子: public class str {
public void method(string s) {
string string = s + "d" // violation.
string = "abc" + "d" // violation.
}
} 更正: 将一个字符的字符串替换成' ' public class str {
public void method(string s) {
string string = s + 'd'
string = "abc" + 'd'
}
} 13、对于 boolean 值,避免不必要的等式判断 将一个 boolean 值与一个 true 比较是一个恒等操作(直接返回该 boolean 变量的值). 移走对于boolean 的不必要操作至少会带来 2 个好处: 1)代码执行的更快 (生成的字节码少了 5 个字节); 2)代码也会更加干净 。 例子: public class ueq {
boolean method (string string) {
return string.endswith ("a") == true; // violation
}
} 更正: class ueq_fixed {
boolean method (string string) {
return string.endswith ("a");
}
} 14、对于常量字符串,用'string' 代替 'stringbuffer' 常量字符串并不需要动态改变长度。 例子: public class usc {
string method () {
stringbuffer s = new stringbuffer ("hello");
string t = s + "world!";
return t;
}
} 更正: 把 stringbuffer 换成 string,如果确定这个 string 不会再变的话,这将会减少运行开销提高性能。 15、用'stringtokenizer' 代替 'indexof()' 和'substring()' 字符串的分析在很多应用中都是常见的。使用 indexof()和 substring()来分析字符串容易导致 stringindexoutofboundsexception。而使用 stringtokenizer 类来分析字符串则会容易一些,效率也会高一些。 例子: public class ust {
void parsestring(string string) {
int index = 0;
while ((index = string.indexof(".", index)) != -1) {
system.out.println (string.substring(index, string.length()));
}
}
} 16、使用条件操作符替代"if (cond) else " 结构 条件操作符更加的简捷 例子: public class if {
public int method(boolean isdone) {
if (isdone) {
return 0;
} else {
return 10;
}


1
2
3
4
5
6
1 void method2(boolean istrue) {  
2    if (istrue) {  
3        _value = 0;  
4    } else {  
5        _value = 1;  
6

<span style="WHITE-SPACE: pre"> </span>}
}
} 更正: public class if {
public int method(boolean isdone) {
return (isdone ? 0 : 10);
}


1
2
3
1void method(boolean istrue) {  
2&lt;span style=&quot;WHITE-SPACE: pre&quot;&gt; &lt;/span&gt;_value = (istrue ? 0 : 1);       // comp  
3

<span style="WHITE-SPACE: pre"> </span>}
private int _value = 0;

} 17、不要在循环体中实例化变量 在循环体中实例化临时变量将会增加内存消耗 例子: import java.util.vector;
public class loop {
void method (vector v) {
for (int i=0;i < v.size();i++) {
object o = new object();
o = v.elementat(i);
}
}
} 更正: 在循环体外定义变量,并反复使用 import java.util.vector;
public class loop {
void method (vector v) {
object o;
for (int i=0;i<v.size();i++) {
o = v.elementat(i);
}
}
} 18、确定 stringbuffer的容量 stringbuffer 的构造器会创建一个默认大小(通常是 16)的字符数组。在使用中,如果超出这个大小,就会重新分配内存,创建一个更大的数组,并将原先的数组复制过来,再丢弃旧的数组。在大多数情况下,你可以在创建 stringbuffer 的时候指定大小,这样就避免了在容量不够的时候自动增长,以提高性能。 例子: public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(); // violation
buffer.append ("hello");
}
} 更正:为 stringbuffer 提供大小。 public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(max);
buffer.append ("hello");
}
private final int max = 100;
} 19、不要总是使用取反操作符(!) 取反操作符(!)降低程序的可读性,所以不要总是使用。 例子: public class dun {
boolean method (boolean a, boolean b) {
if (!a)
return !a;
else
return !b;
}
} 更正:如果可能不要使用取反操作符(!) 20、与一个接口 进行instanceof 操作 基于接口的设计通常是件好事,因为它允许有不同的实现,而又保持灵活。只要可能,对一个对象进行 instanceof 操作,以判断它是否某一接口要比是否某一个类要快。 例子: public class insof {
private void method (object o) {
if (o instanceof interfacebase) { } // better
if (o instanceof classbase) { } // worse.
}
}

class classbase {}
interface interfacebase {} 21、采用在需要的时候才开始创建的策略。 例如: String str="abc";
if(i==1){ list.add(str);} 应修改为: if(i==1){String str="abc"; list.add(str);} 22、通过 StringBuffer 的构造函数来设定他的初始化容量,可以明显提升性能。 StringBuffer 的默认容量为 16,当 StringBuffer 的容量达到最大容量时,她会将自身容量增加到当前的 2 倍+2,也就是 2n+2。无论何时,只要 StringBuffer 到达她的最大容量,她就不得不创建一个新的对象数组,然后复制旧的对象数组,这会浪费很多时间。所以给StringBuffer 设置一个合理的初始化容量值,是很有必要的! 23、合理使用 java.util.Vector Vector 与 StringBuffer 类似,每次扩展容量时,所有现有元素都要赋值到新的存储空间中。Vector 的默认存储能力为 10个元素,扩容加倍。 vector.add(index,obj) 这个方法可以将元素 obj 插入到index 位置,但 index 以及之后的元素依次都要向下移动一个位置(将其索引加 1)。 除非必要,否则对性能不利。 同样规则适用于 remove(int index)方法,移除此向量中指定位置的元素。将所有后续元素左移(将其索引减 1)。返回此向量中移除的元素。所以删除 vector 最后一个元素要比删除第1 个元素开销低很多。删除所有元素最好用 removeAllElements()方法。 如果要删除 vector 里的一个元素可以使用 vector.remove(obj);而不必自己检索元素位置,再删除,如 int index = indexOf(obj);vector.remove(index); 24、不要将数组声明为:public static final 25、HaspMap 的遍历 Map<String, String[]> paraMap = new HashMap<String, String[]>();
for( Entry<String, String[]> entry : paraMap.entrySet() )
{
String appFieldDefId = entry.getKey();
String[] values = entry.getValue();
} 利用散列值取出相应的 Entry 做比较得到结果,取得 entry的值之后直接取 key和 value。 26、array(数组)和 ArrayList 的使用。 array 数组效率最高,但容量固定,无法动态改变,ArrayList 容量可以动态增长,但牺牲了效率。 27、StringBuffer,StringBuilder 的区别 StringBuffer,StringBuilder 的区别在于:java.lang.StringBuffer 线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。StringBuilder 与该类相比,通常应该优先使用 StringBuilder 类,因为她支持所有相同的操作,但由于她不执行同步,所以速度更快。为了获得更好的性能,在构造 StringBuffer 或 StringBuilder 时应尽量指定她的容量。当然如果不超过 16 个字符时就不用了。 相同情况下,使用 StringBuilder 比使用 StringBuffer 仅能获得 10%~15%的性能提升,但却要冒多线程不安全的风险。综合考虑还是建议使用 StringBuffer。 28、 尽量使用基本数据类型代替对象。 29、用简单的数值计算代替复杂的函数计算,比如查表方式解决三角函数问题。 30、使用具体类比使用接口效率高,但结构弹性降低了,但现代 IDE 都可以解决这个问题。 31、考虑使用静态方法 如果你没有必要去访问对象的外部,那么就使你的方法成为静态方法。她会被更快地调用,因为她不需要一个虚拟函数导向表。这同事也是一个很好的实践,因为她告诉你如何区分方法的性质,调用这个方法不会改变对象的状态。 32.应尽可能避免使用内在的GET,SET 方法 android 编程中,虚方法的调用会产生很多代价,比实例属性查询的代价还要多。我们应该在外包调用的时候才使用 get,set方法,但在内部调用的时候,应该直接调用。 33、避免枚举,浮点数的使用。 34、二维数组比一维数组占用更多的内存空间,大概是 10 倍计算。 35、SQLite SQLite 数据库读取整张表的全部数据很快,但有条件的查询就要耗时 30-50MS,大家做这方面的时候要注意,尽量少用,尤其是嵌套查找! 36、奇偶判断 不要使用 i % 2 == 1 来判断是否是奇数,因为 i为负奇数时不成立,请使用 i % 2 != 0 来判断是否是奇数,或使用 高效式 (i & 1) != 0 来判断。 |public static Credit getNewCredit()
{
return new Credit();
} |private static Credit BaseCredit = new Credit();
public static Credit getNewCredit()
{
return (Credit)BaseCredit.clone();
} |public class usv {
void getsum (int[] values) {
for (int i=0; i < value.length; i++) {
_sum += value[i]; // violation.
}
}
void getsum2 (int[] values) {
for (int i=0; i < value.length; i++) {
_staticsum += value[i];
}
}
private int _sum;
private static int _staticsum;
} |void getsum (int[] values) {
int sum = _sum; // temporary local variable.
for (int i=0; i < value.length; i++) {
sum += value[i];
}
_sum = sum; |class maf {
public void setsize (int size) {
_size = size;
}
private int _size;
} |class daf_fixed {
final public void setsize (int size) {
_size = size;
}
private int _size;
} |public class uiso {
public uiso () {}
}
class dog extends uiso {
void method (dog dog, uiso u) {
dog d = dog;
if (d instanceof uiso) // always true.
system.out.println("dog is a uiso");
uiso uiso = u;
if (uiso instanceof object) // always true.
system.out.println("uiso is an object");
}
} |class dog extends uiso {
void method () {
dog d;
system.out.println ("dog is an uiso");
system.out.println ("uiso is an uiso");
}
} |class unc {
string _id = "unc";
}
class dog extends unc {
void method () {
dog dog = new dog ();
unc animal = (unc)dog; // not necessary.
object o = (object)dog; // not necessary.
}
} |class dog extends unc {
void method () {
dog dog = new dog();
unc animal = dog;
object o = dog;
}
} |import java.io.
;
public class cs {
public static void main (string args[]) {
cs cs = new cs ();
cs.method ();
}
public void method () {
try {
fileinputstream fis = new fileinputstream ("cs.java");
int count = 0;
while (fis.read () != -1)
count++;
system.out.println (count);
fis.close ();
} catch (filenotfoundexception e1) {
} catch (ioexception e2) {
}
}
} |import java.io.fileinputstream;
public class try {
void method (fileinputstream fis) {
for (int i = 0; i < size; i++) {
try { // violation
_sum += fis.read();
} catch (exception e) {}
}
}
private int _sum;
} |void method (fileinputstream fis) {
try {
for (int i = 0; i < size; i++) { _sum += fis.read();
}
} catch (exception e) {}
} |import java.util.vector;
public class syn {
public synchronized void method (object o) {
}
private void test () {
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i)); // violation
}
}
private vector vector = new vector (5, 5);
} |import java.util.vector;
public class syn {
public void method (object o) {
}
private void test () {
synchronized{//在一个同步块中执行非同步方法
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i));
}
}
}
private vector vector = new vector (5, 5);
} |public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a / 4; // should be replaced with "a >> 2".
int div2 = a / 8; // should be replaced with "a >> 3".
int temp = a / 3;
int mul = a * 4; // should be replaced with "a << 2".
int mul2 = 8 * a; // should be replaced with "a << 3".
int temp2 = a * 3;
}
} |public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a >> 2;
int div2 = a >> 3;
int temp = a / 3; // 不能转换成位移操作
int mul = a << 2;
int mul2 = a << 3;
int temp = a * 3; // 不能转换
}
} |public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
for (int i = 0; i < array2.length; i++) {
array2 [i] = array1 [i]; // violation
}
}
} |public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
system.arraycopy(array1, 0, array2, 0, 100);
}
} |Vector aVector= …;
for(int i=0;i<aVector size();i++)(
System out printlll(aVector elementAt(i)toStringO);
} |Vector aVector= …:
int length=aVector size();
for(int i=0;i<length;i++)f
System out println(aVector elememAt(i)toStringO);
) |import java.util.vector;
public class dic {
public void addobjects (object[] o) {
// if length > 10, vector needs to expand
for (int i = 0; i< o.length;i++) {
v.add(o); // capacity before it can add more elements.
}
}
public vector v = new vector(); // no initialcapacity.
} |<span style="WHITE-SPACE: pre"> </span><span style="font-size:14px;">更正: 自己设定初始大小。 </span> |public vector v = new vector(20);
public hashtable hash = new hashtable(10); |public class pcts {
private void method(string s) {
if (s.startswith("a")) { // violation
// …
}
}
} |public class pcts {
private void method(string s) {
if ('a' == s.charat(0)) {
// …
}
}
} |public class str {
public void method(string s) {
string string = s + "d" // violation.
string = "abc" + "d" // violation.
}
} |public class str {
public void method(string s) {
string string = s + 'd'
string = "abc" + 'd'
}
} |public class ueq {
boolean method (string string) {
return string.endswith ("a") == true; // violation
}
} |class ueq_fixed {
boolean method (string string) {
return string.endswith ("a");
}
} |public class usc {
string method () {
stringbuffer s = new stringbuffer ("hello");
string t = s + "world!";
return t;
}
} |public class ust {
void parsestring(string string) {
int index = 0;
while ((index = string.indexof(".", index)) != -1) {
system.out.println (string.substring(index, string.length()));
}
}
} |public class if {
public int method(boolean isdone) {
if (isdone) {
return 0;
} else {
return 10;
}


1
2
3
4
5
6
1 void method2(boolean istrue) {  
2    if (istrue) {  
3        _value = 0;  
4    } else {  
5        _value = 1;  
6

<span style="WHITE-SPACE: pre"> </span>}
}
} |public class if {
public int method(boolean isdone) {
return (isdone ? 0 : 10);
}


1
2
3
1void method(boolean istrue) {  
2&lt;span style=&quot;WHITE-SPACE: pre&quot;&gt; &lt;/span&gt;_value = (istrue ? 0 : 1);       // comp  
3

<span style="WHITE-SPACE: pre"> </span>}
private int _value = 0;

} |import java.util.vector;
public class loop {
void method (vector v) {
for (int i=0;i < v.size();i++) {
object o = new object();
o = v.elementat(i);
}
}
} |import java.util.vector;
public class loop {
void method (vector v) {
object o;
for (int i=0;i<v.size();i++) {
o = v.elementat(i);
}
}
} |public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(); // violation
buffer.append ("hello");
}
} |public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(max);
buffer.append ("hello");
}
private final int max = 100;
} |public class dun {
boolean method (boolean a, boolean b) {
if (!a)
return !a;
else
return !b;
}
} |public class insof {
private void method (object o) {
if (o instanceof interfacebase) { } // better
if (o instanceof classbase) { } // worse.
}
}

class classbase {}
interface interfacebase {} |String str="abc";
if(i==1){ list.add(str);} |if(i==1){String str="abc"; list.add(str);} |Map<String, String[]> paraMap = new HashMap<String, String[]>();
for( Entry<String, String[]> entry : paraMap.entrySet() )
{
String appFieldDefId = entry.getKey();
String[] values = entry.getValue();
} |
| 写Java也有n年了,现在还是有不少的坏的代码习惯,也通过学习别人的代码学到了不少好的习惯。这篇文章主要是整理的资料。留给自己做个警戒,提示以后写代码的时候注意!在文章的后面,会提供整理的原材料下载。 一、类和对象使用技巧 1、尽量少用new生成新对象 用new创建类的实例时,构造雨数链中所有构造函数都会被自动调用,操作速度较慢。在某些时候可复用现有对象。比如在进行大量St rillg操作时,可用StringBuffer娄代替String类,以避免生成大量的对象。用 new关键词创建类的实例时,构造函数链中的所有构造函数都会被自动调用。但如果一个对象实现了 Cloneable 接口,我们可以调用她的 clone() 方法。clone()方法不会调用任何类构造函数。 下面是 Factory 模式的一个典型实现。 public static Credit getNewCredit()
{
return new Credit();
} 改进后的代码使用 clone() 方法, private static Credit BaseCredit = new Credit();
public static Credit getNewCredit()
{
return (Credit)BaseCredit.clone();
} 2、使用clone()方法生成新对象 如果一个对象实现Cloneable接口,就可以调用它的clone()方法。clone()方法不会泪用任何类构造函数,比使用new方法创建实例速度要快。 3、尽量使用局部变量(栈变量) 调用方法时传递的参数及调用中创建的临时变量保存在栈(Stack)中,速度较快。其他变量,如静态变量、实例变量都在堆(HeaP)中创建,速度较慢。访问静态变量和实例变量将会比访问局部变量多耗费 2-3 个时钟周期。如果一个变量需要经常访问,那么你就需要考虑这个变量的作用域了。static? local?还是实例变量? 调用方法时传递的参数以及在调用中创建的临时变量都保存在栈(Stack)中,速度较快。其他变量,如静态变量,实例变量等,都在堆(Heap)中创建,速度较慢。 例子: public class usv {
void getsum (int[] values) {
for (int i=0; i < value.length; i++) {
_sum += value[i]; // violation.
}
}
void getsum2 (int[] values) {
for (int i=0; i < value.length; i++) {
_staticsum += value[i];
}
}
private int _sum;
private static int _staticsum;
} 更正:如果可能,请使用局部变量作为你经常访问的变量。 你可以按下面的方法来修改 getsum()方法: void getsum (int[] values) {
int sum = _sum; // temporary local variable.
for (int i=0; i < value.length; i++) {
sum += value[i];
}
_sum = sum; 4、减少方法调用 面向对象设计的一个基本准则是通过方法间接访问对象的属性,但方法调用会占用·些开销访问。可以避免在同一个类中通过训州函数或方法(get或set)来设置或调用该对象的灾例变量,这比直接访问变量要慢。为了减少方法调用,可以将方法中的代码复制到调用方法的地方,比如大量的循环中,这样可以节省方法调用的开销。但带来性能提升的同时会牺牲代码的可读性,可根据实际需要平衡两者关系。 5、使用final类和final、static、private方法 带有final修饰符的类是不可派生的。如果指定一个类为finaI,则该类所有的方法都是final。JAVA编障器会寻找机会内联(inIine)所有的final方法。此举能够提升程序性能。使用final、static、private的方法是不能被覆盖的,JAVA不需要在稃序运行的时候动态关联实现方法,从而节省了运行时间。 带有 final 修饰符的类是不可派生的。在 JAVA核心 API中,有许多应用 final 的例子,例如 java.lang.String。为 String 类指定 final 防止了使用者覆盖 length()方法。另外,如果一个类是 final 的,则该类所有方法都是 final 的。java 编译器会寻找机会内联(inline)所有的final 方法(这和具体的编译器实现有关)。此举能够使性能平均提高 50%。 6、让访问实例内变量的 getter/setter 方法变成”final” 简单的 getter/setter 方法应该被置成 final,这会告诉编译器,这个方法不会被重载,所以,可以变成”inlined” 例子: class maf {
public void setsize (int size) {
_size = size;
}
private int _size;
} 更正: class daf_fixed {
final public void setsize (int size) {
_size = size;
}
private int _size;
} 7、避免不需要的 instanceof 操作 如果左边的对象的静态类型等于右边的,instanceof 表达式返回永远为 true。 例子: public class uiso {
public uiso () {}
}
class dog extends uiso {
void method (dog dog, uiso u) {
dog d = dog;
if (d instanceof uiso) // always true.
system.out.println("dog is a uiso");
uiso uiso = u;
if (uiso instanceof object) // always true.
system.out.println("uiso is an object");
}
} 更正:删掉不需要的 instanceof 操作。 class dog extends uiso {
void method () {
dog d;
system.out.println ("dog is an uiso");
system.out.println ("uiso is an uiso");
}
} 8、避免不需要的造型操作 所有的类都是直接或者间接继承自 object。同样,所有的子类也都隐含的“等于”其父类。那么,由子类造型至父类的操作就是不必要的了。  例子: class unc {
string _id = "unc";
}
class dog extends unc {
void method () {
dog dog = new dog ();
unc animal = (unc)dog; // not necessary.
object o = (object)dog; // not necessary.
}
} 更正: class dog extends unc {
void method () {
dog dog = new dog();
unc animal = dog;
object o = dog;
}
} 9.尽量重用对象。 特别是 String 对象的使用中,出现字符串连接情况时应使用 StringBuffer 代替,由于系统不仅要花时间生成对象,以后可能还需要花时间对这些对象进行垃圾回收和处理。因此生成过多的对象将会给程序的性能带来很大的影响。 10、不要重复初始化变量。 默认情况下,调用类的构造函数时,java 会把变量初始化成确定的值,所有的对象被设置成null,整数变量设置成 0,float 和 double 变量设置成 0.0,逻辑值设置成 false。当一个类从另一个类派生时,这一点尤其应该注意,因为用 new 关键字创建一个对象时,构造函数链中的所有构造函数都会被自动调用。 这里有个注意,给成员变量设置初始值但需要调用其他方法的时候,最好放在一个方法比如initXXX()中,因为直接调用某方法赋值可能会因为类尚未初始化而抛空指针异常,public int state = this.getState(); 11、不要过分创建对象 过分的创建对象会消耗系统的大量内存,严重时,会导致内存泄漏,因此,保证过期的对象的及时回收具有重要意义。 JVM 的 GC并非十分智能,因此建议在对象使用完毕后,手动设置成 null。 二、Java I/O技巧 I/O性能常常是应用程序性能瓶颈,优化I/O性能就显得极为系要。在进行I/0操作时,匿遵循以下原则:尽可能少的访问磁盘;尽可能少的I方问底层的操作系统;尽可能少的方法调用;尽可能少处理个别的处理字节和字符。基于以上原则,可以通过以下技巧提高I/O速度: 1、使州缓冲提高I/O性能。 常用的实现方法有以下2种:使用用于字符的BufferedReader和用于宁节的BufferedlnputStream类,或者使用块读取方法次读取一大块数据。 2、lnputStream比Reader高效,OutputStream比Writer高效。 当使用Unicode字符串时,Write类的开销比较大。因为它要实Uoicode到字节(byte)的转换。因此,如果可能的话,在使用 Write类之前就实现转换或用OutputStream类代替Writer娄来使用。 3、在适当的时候用byte替代char。 1个char用2个字节保存字符,而byte只需要1个,因此用byte保存字符消耗的内存和需要执行的机器指令更少。更重要的是,用byte避免了进行Unicode转换。因此,如果町能的话,应尽量使用byte替代char。 4、有缓冲的块操作10要比缓冲的流字符IO快。 对于字符IO,虽然缓冲流避免了每次读取字符时的系统调用开销,但仍需要一次或多次方法调用。带缓冲的块10比缓冲流IO快2到4倍,比无缓冲的IO快4到40倍。 5、序列化时,使用原子类型。 当序列化一个类或对象时,对干那些原子类型(atomic)或可以重建的元素,要标识为transient类型,这样就不用每一次都进行序列化。如果这砦序列化的对象要在网络上传输,这一小小的改变对性能会有很大的提高。 6、在finally 块中关闭stream 程序中使用到的资源应当被释放,以避免资源泄漏。这最好在 finally 块中去做。不管程序执行的结果如何,finally 块总是会执行的,以确保资源的正确关闭。 例子: import java.io.*;
public class cs {
public static void main (string args[]) {
cs cs = new cs ();
cs.method ();
}
public void method () {
try {
fileinputstream fis = new fileinputstream ("cs.java");
int count = 0;
while (fis.read () != -1)
count++;
system.out.println (count);
fis.close ();
} catch (filenotfoundexception e1) {
} catch (ioexception e2) {
}
}
} 更正: 在最后一个 catch 后添加一个 finally 块 7、SQL语句 在 java+Oracle 的应用系统开发中,java 中内嵌的 SQL 语言应尽量使用大写形式,以减少Oracle 解析器的解析负担。 8、尽早释放资源 java 编程过程中,进行数据库连接,I/O 流操作,在使用完毕后,及时关闭以释放资源。因为对这些大对象的操作会造成系统大的开销。 三、异常(Exceptions)使用技巧 JAVA语言中提供了try/catch来开发方便用户捕捉异常,进行异常的处理。但是如果使用不当,也会给JAvA程序的性能带来影响。因此,要注意以下儿点。慎用异常,异常对性能不利。抛出异常首先要创建一个新的对象。Throwable接口的构造函数调用名为fillInStackTrace()的本地(Native)方法filllnStackTrace()方法检查堆栈,收集调用跟踪信息。只要有异常被抛出,VM就必须调整调用堆栈。 1、避免使用异常来控制程序流程 如果可以用if、while等逻辑语句来处理,那么就尽可能的不用try/catch语句。抛出异常首先要创建一个新的对象。Throwable 接口的构造函数调用名为 fillInStackTrace()的本地方法,fillInStackTrace()方法检查栈,收集调用跟踪信息。只要有异常被抛出,VM 就必须调整调用栈,因为在处理过程中创建了一个新的对象。 异常只能用于错误处理,不应该用来控制程序流程。 2、尽可能重用异常 在必须要进行异常的处理时,要尽可能的重用已经存在的异常对象。因为在异常的处理中,生成个异常对象要消耗掉大部分的时间。 3、将try/catch 块移出循环 把try/catch块放入循环体内,会极大的影响性能,如果编译 jit 被关闭或者你所使用的是一个不带 jit 的jvm,性能会将下降21%之多! 例子: import java.io.fileinputstream;
public class try {
void method (fileinputstream fis) {
for (int i = 0; i < size; i++) {
try { // violation
_sum += fis.read();
} catch (exception e) {}
}
}
private int _sum;
} 更正:将 try/catch块移出循环 void method (fileinputstream fis) {
try {
for (int i = 0; i < size; i++) { sum += fis.read();
}
} catch (exception e) {}
} 四、线程使用技巧 1、在使用大量线程(Threading)的场合使用线程池管理 生成和启动新线程是个相对较慢的过程,生成人量新线程会严重影响应J
}j程序性能。通过使用线程池,由线程池管理器(thread pool manager)来生成新线程或分配现有线程,柏省生成线程的叫间。 2、防止过多的同步 不必要的同步常常会造成程序性能的下降,调用同步方法比调用非同步方法要花费更多的时间。如果程序是单线程,则没有必要使用同步。 3、同步方法而不要同步整个代码段 对某个方法或函数进行同步比对整个代码段进行同步的性能要好。 4、在追求速度的场合,用ArrayList和HashMap代替Vector和Hashtable Vector和Hashtable实现了同步以提高线程安全性,但速度较没有实现同步的ArrayList和Ha shMap要慢,可以根据需要选择使用的类。 5、使用notify()而不是notifyAll() 使用哪个方法要取决于程序的没计,但应尽可能使用notify(),因为notify()只唤醒等待指定对象的线程,比唤醒所有等待线稃的notifyAll0速度更快。 6、不要在循环中调用 synchronized(同步)方法 方法的同步需要消耗相当大的资料,在一个循环中调用它绝对不是一个好主意。 例子: import java.util.vector;
public class syn {
public synchronized void method (object o) {
}
private void test () {
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i)); // violation
}
}
private vector vector = new vector (5, 5);
} 更正:不要在循环体中调用同步方法,如果必须同步的话,推荐以下方式: import java.util.vector;
public class syn {
public void method (object o) {
}
private void test () {
synchronized{//在一个同步块中执行非同步方法
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i));
}
}
}
private vector vector = new vector (5, 5);
} 7、单线程应尽量使用 HashMap, ArrayList。 除非必要,否则不推荐使用 HashTable,Vector,她们使用了同步机制,而降低了性能。 五、其它常用技巧 1、使用移位操作替代乘除法操作可以极大地提高性能 "/"是一个很“昂贵”的操作,使用移位操作将会更快更有效。 例子: public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a / 4; // should be replaced with "a >> 2".
int div2 = a / 8; // should be replaced with "a >> 3".
int temp = a / 3;
int mul = a * 4; // should be replaced with "a << 2".
int mul2 = 8 * a; // should be replaced with "a << 3".
int temp2 = a * 3;
}
} 更正: public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a >> 2;
int div2 = a >> 3;
int temp = a / 3; // 不能转换成位移操作
int mul = a << 2;
int mul2 = a << 3;
int temp = a * 3; // 不能转换
}
} PS:除非是在一个非常大的循环内,性能非常重要,而且你很清楚你自己在做什么,方可使用这种方法。否则提高性能所带来的程序晚读性的降低将是不合算的。 2、对Vector中最后位置的添加、删除操作要远远快于埘第一个元素的添加、删除操作 3、当复制数组时,使用System.arraycop()方法 例子: public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
for (int i = 0; i < array2.length; i++) {
array2 [i] = array1 [i]; // violation
}
}
} 更正: public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
system.arraycopy(array1, 0, array2, 0, 100);
}
} 4、使用复合赋值运算符 a=a+b和a+b住编译时会产生不同JAVA字奇码,后者回快于前者。冈此,使用+=、-=、+=、/=等复台赋值运算符会使运算速度稍有提升。 5、用int而不用其它基本类型 对int类犁的操作通常比其它基本类型要快,因此尽量使用int类型。 6、在进行数据库连接和网络连接时使用连接池 这类连接往往会耗费大量时间,应尽量避免。可以使用连接池技术,复用现有连接。 7、用压缩加快网络传输速度一种常用方法是把相关文件打包到一个jar文件中。 用一个Jar文件发送多个文件还叫以避免每个文件打开和关闭网络连接所造成的开销。 8、在数据库应用程序中使用批处理功能 可以利用Statement类的addBatch()氟l exexuteBatch法成批地提交sql语句,以节省网络传输开销。在执行大量相似语句时,可以使用PreParedState—类,它可以一次性编译语句并多次执行,用参数最后执行的sql语句。 9、消除循环体中不必要的代码 这似乎是每个程序员都知道的基本原则,没有必出,但很多人往往忽略一些细节。如下列代码: Vector aVector= …;
for(int i=0;i<aVector size();i++)(
System out printlll(aVector elementAt(i)toStringO);
} 这段代码中没循环一次就要调用aVector.size()方法,aVector的长度不变的话,可以改为一下代码: Vector aVector= …:
int length=aVector size();
for(int i=0;i<length;i++)f
System out println(aVector elememAt(i)toStringO);
) 这样消除了每次调用aVector.size()方法的开销。 10、为'vectors' 和 'hashtables'定义初始大小 jvm 为 vector 扩充大小的时候需要重新创建一个更大的数组,将原原先数组中的内容复制过来,最后,原先的数组再被回收。可见 vector 容量的扩大是一个颇费时间的事。 通常,默认的 10 个元素大小是不够的。你最好能准确的估计你所需要的最佳大小。 例子: import java.util.vector;
public class dic {
public void addobjects (object[] o) {
// if length > 10, vector needs to expand
for (int i = 0; i< o.length;i++) {
v.add(o); // capacity before it can add more elements.
}
}
public vector v = new vector(); // no initialcapacity.
} <span style="WHITE-SPACE: pre"> </span><span style="font-size:14px;">更正: 自己设定初始大小。 </span> public vector v = new vector(20);
public hashtable hash = new hashtable(10); 11、如果只是查找单个字符的话,用charat()代替startswith() 用一个字符作为参数调用 startswith()也会工作的很好,但从性能角度上来看,调用用 string api 无疑是错误的! 例子: public class pcts {
private void method(string s) {
if (s.startswith("a")) { // violation
// …
}
}
} 更正 :将'startswith()' 替换成'charat()'. public class pcts {
private void method(string s) {
if ('a' == s.charat(0)) {
// …
}
}
} 12、在字符串相加的时候,使用 ' ' 代替 " ",如果该字符串只有一个字符的话 例子: public class str {
public void method(string s) {
string string = s + "d" // violation.
string = "abc" + "d" // violation.
}
} 更正: 将一个字符的字符串替换成' ' public class str {
public void method(string s) {
string string = s + 'd'
string = "abc" + 'd'
}
} 13、对于 boolean 值,避免不必要的等式判断 将一个 boolean 值与一个 true 比较是一个恒等操作(直接返回该 boolean 变量的值). 移走对于boolean 的不必要操作至少会带来 2 个好处: 1)代码执行的更快 (生成的字节码少了 5 个字节); 2)代码也会更加干净 。 例子: public class ueq {
boolean method (string string) {
return string.endswith ("a") == true; // violation
}
} 更正: class ueq_fixed {
boolean method (string string) {
return string.endswith ("a");
}
} 14、对于常量字符串,用'string' 代替 'stringbuffer' 常量字符串并不需要动态改变长度。 例子: public class usc {
string method () {
stringbuffer s = new stringbuffer ("hello");
string t = s + "world!";
return t;
}
} 更正: 把 stringbuffer 换成 string,如果确定这个 string 不会再变的话,这将会减少运行开销提高性能。 15、用'stringtokenizer' 代替 'indexof()' 和'substring()' 字符串的分析在很多应用中都是常见的。使用 indexof()和 substring()来分析字符串容易导致 stringindexoutofboundsexception。而使用 stringtokenizer 类来分析字符串则会容易一些,效率也会高一些。 例子: public class ust {
void parsestring(string string) {
int index = 0;
while ((index = string.indexof(".", index)) != -1) {
system.out.println (string.substring(index, string.length()));
}
}
} 16、使用条件操作符替代"if (cond) else " 结构 条件操作符更加的简捷 例子: public class if {
public int method(boolean isdone) {
if (isdone) {
return 0;
} else {
return 10;
}


1
2
3
4
5
6
1 void method2(boolean istrue) {  
2    if (istrue) {  
3        _value = 0;  
4    } else {  
5        _value = 1;  
6

<span style="WHITE-SPACE: pre"> </span>}
}
} 更正: public class if {
public int method(boolean isdone) {
return (isdone ? 0 : 10);
}


1
2
3
1void method(boolean istrue) {  
2&lt;span style=&quot;WHITE-SPACE: pre&quot;&gt; &lt;/span&gt;_value = (istrue ? 0 : 1);       // comp  
3

<span style="WHITE-SPACE: pre"> </span>}
private int _value = 0;

} 17、不要在循环体中实例化变量 在循环体中实例化临时变量将会增加内存消耗 例子: import java.util.vector;
public class loop {
void method (vector v) {
for (int i=0;i < v.size();i++) {
object o = new object();
o = v.elementat(i);
}
}
} 更正: 在循环体外定义变量,并反复使用 import java.util.vector;
public class loop {
void method (vector v) {
object o;
for (int i=0;i<v.size();i++) {
o = v.elementat(i);
}
}
} 18、确定 stringbuffer的容量 stringbuffer 的构造器会创建一个默认大小(通常是 16)的字符数组。在使用中,如果超出这个大小,就会重新分配内存,创建一个更大的数组,并将原先的数组复制过来,再丢弃旧的数组。在大多数情况下,你可以在创建 stringbuffer 的时候指定大小,这样就避免了在容量不够的时候自动增长,以提高性能。 例子: public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(); // violation
buffer.append ("hello");
}
} 更正:为 stringbuffer 提供大小。 public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(max);
buffer.append ("hello");
}
private final int max = 100;
} 19、不要总是使用取反操作符(!) 取反操作符(!)降低程序的可读性,所以不要总是使用。 例子: public class dun {
boolean method (boolean a, boolean b) {
if (!a)
return !a;
else
return !b;
}
} 更正:如果可能不要使用取反操作符(!) 20、与一个接口 进行instanceof 操作 基于接口的设计通常是件好事,因为它允许有不同的实现,而又保持灵活。只要可能,对一个对象进行 instanceof 操作,以判断它是否某一接口要比是否某一个类要快。 例子: public class insof {
private void method (object o) {
if (o instanceof interfacebase) { } // better
if (o instanceof classbase) { } // worse.
}
}

class classbase {}
interface interfacebase {} 21、采用在需要的时候才开始创建的策略。 例如: String str="abc";
if(i==1){ list.add(str);} 应修改为: if(i==1){String str="abc"; list.add(str);} 22、通过 StringBuffer 的构造函数来设定他的初始化容量,可以明显提升性能。 StringBuffer 的默认容量为 16,当 StringBuffer 的容量达到最大容量时,她会将自身容量增加到当前的 2 倍+2,也就是 2n+2。无论何时,只要 StringBuffer 到达她的最大容量,她就不得不创建一个新的对象数组,然后复制旧的对象数组,这会浪费很多时间。所以给StringBuffer 设置一个合理的初始化容量值,是很有必要的! 23、合理使用 java.util.Vector Vector 与 StringBuffer 类似,每次扩展容量时,所有现有元素都要赋值到新的存储空间中。Vector 的默认存储能力为 10个元素,扩容加倍。 vector.add(index,obj) 这个方法可以将元素 obj 插入到index 位置,但 index 以及之后的元素依次都要向下移动一个位置(将其索引加 1)。 除非必要,否则对性能不利。 同样规则适用于 remove(int index)方法,移除此向量中指定位置的元素。将所有后续元素左移(将其索引减 1)。返回此向量中移除的元素。所以删除 vector 最后一个元素要比删除第1 个元素开销低很多。删除所有元素最好用 removeAllElements()方法。 如果要删除 vector 里的一个元素可以使用 vector.remove(obj);而不必自己检索元素位置,再删除,如 int index = indexOf(obj);vector.remove(index); 24、不要将数组声明为:public static final 25、HaspMap 的遍历 Map<String, String[]> paraMap = new HashMap<String, String[]>();
for( Entry<String, String[]> entry : paraMap.entrySet() )
{
String appFieldDefId = entry.getKey();
String[] values = entry.getValue();
} 利用散列值取出相应的 Entry 做比较得到结果,取得 entry的值之后直接取 key和 value。 26、array(数组)和 ArrayList 的使用。 array 数组效率最高,但容量固定,无法动态改变,ArrayList 容量可以动态增长,但牺牲了效率。 27、StringBuffer,StringBuilder 的区别 StringBuffer,StringBuilder 的区别在于:java.lang.StringBuffer 线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。StringBuilder 与该类相比,通常应该优先使用 StringBuilder 类,因为她支持所有相同的操作,但由于她不执行同步,所以速度更快。为了获得更好的性能,在构造 StringBuffer 或 StringBuilder 时应尽量指定她的容量。当然如果不超过 16 个字符时就不用了。 相同情况下,使用 StringBuilder 比使用 StringBuffer 仅能获得 10%~15%的性能提升,但却要冒多线程不安全的风险。综合考虑还是建议使用 StringBuffer。 28、 尽量使用基本数据类型代替对象。 29、用简单的数值计算代替复杂的函数计算,比如查表方式解决三角函数问题。 30、使用具体类比使用接口效率高,但结构弹性降低了,但现代 IDE 都可以解决这个问题。 31、考虑使用静态方法 如果你没有必要去访问对象的外部,那么就使你的方法成为静态方法。她会被更快地调用,因为她不需要一个虚拟函数导向表。这同事也是一个很好的实践,因为她告诉你如何区分方法的性质,调用这个方法不会改变对象的状态。 32.应尽可能避免使用内在的GET,SET 方法 android 编程中,虚方法的调用会产生很多代价,比实例属性查询的代价还要多。我们应该在外包调用的时候才使用 get,set方法,但在内部调用的时候,应该直接调用。 33、避免枚举,浮点数的使用。 34、二维数组比一维数组占用更多的内存空间,大概是 10 倍计算。 35、SQLite SQLite 数据库读取整张表的全部数据很快,但有条件的查询就要耗时 30-50MS,大家做这方面的时候要注意,尽量少用,尤其是嵌套查找! 36、奇偶判断 不要使用 i % 2 == 1 来判断是否是奇数,因为 i为负奇数时不成立,请使用 i % 2 != 0 来判断是否是奇数,或使用 高效式 (i & 1) != 0 来判断。 |public static Credit getNewCredit()
{
return new Credit();
} |private static Credit BaseCredit = new Credit();
public static Credit getNewCredit()
{
return (Credit)BaseCredit.clone();
} |public class usv {
void getsum (int[] values) {
for (int i=0; i < value.length; i++) {
_sum += value[i]; // violation.
}
}
void getsum2 (int[] values) {
for (int i=0; i < value.length; i++) {
_staticsum += value[i];
}
}
private int _sum;
private static int _staticsum;
} |void getsum (int[] values) {
int sum = _sum; // temporary local variable.
for (int i=0; i < value.length; i++) {
sum += value[i];
}
_sum = sum; |class maf {
public void setsize (int size) {
_size = size;
}
private int _size;
} |class daf_fixed {
final public void setsize (int size) {
_size = size;
}
private int _size;
} |public class uiso {
public uiso () {}
}
class dog extends uiso {
void method (dog dog, uiso u) {
dog d = dog;
if (d instanceof uiso) // always true.
system.out.println("dog is a uiso");
uiso uiso = u;
if (uiso instanceof object) // always true.
system.out.println("uiso is an object");
}
} |class dog extends uiso {
void method () {
dog d;
system.out.println ("dog is an uiso");
system.out.println ("uiso is an uiso");
}
} |class unc {
string _id = "unc";
}
class dog extends unc {
void method () {
dog dog = new dog ();
unc animal = (unc)dog; // not necessary.
object o = (object)dog; // not necessary.
}
} |class dog extends unc {
void method () {
dog dog = new dog();
unc animal = dog;
object o = dog;
}
} |import java.io.
;
public class cs {
public static void main (string args[]) {
cs cs = new cs ();
cs.method ();
}
public void method () {
try {
fileinputstream fis = new fileinputstream ("cs.java");
int count = 0;
while (fis.read () != -1)
count++;
system.out.println (count);
fis.close ();
} catch (filenotfoundexception e1) {
} catch (ioexception e2) {
}
}
} |import java.io.fileinputstream;
public class try {
void method (fileinputstream fis) {
for (int i = 0; i < size; i++) {
try { // violation
_sum += fis.read();
} catch (exception e) {}
}
}
private int _sum;
} |void method (fileinputstream fis) {
try {
for (int i = 0; i < size; i++) { _sum += fis.read();
}
} catch (exception e) {}
} |import java.util.vector;
public class syn {
public synchronized void method (object o) {
}
private void test () {
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i)); // violation
}
}
private vector vector = new vector (5, 5);
} |import java.util.vector;
public class syn {
public void method (object o) {
}
private void test () {
synchronized{//在一个同步块中执行非同步方法
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i));
}
}
}
private vector vector = new vector (5, 5);
} |public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a / 4; // should be replaced with "a >> 2".
int div2 = a / 8; // should be replaced with "a >> 3".
int temp = a / 3;
int mul = a * 4; // should be replaced with "a << 2".
int mul2 = 8 * a; // should be replaced with "a << 3".
int temp2 = a * 3;
}
} |public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a >> 2;
int div2 = a >> 3;
int temp = a / 3; // 不能转换成位移操作
int mul = a << 2;
int mul2 = a << 3;
int temp = a * 3; // 不能转换
}
} |public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
for (int i = 0; i < array2.length; i++) {
array2 [i] = array1 [i]; // violation
}
}
} |public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
system.arraycopy(array1, 0, array2, 0, 100);
}
} |Vector aVector= …;
for(int i=0;i<aVector size();i++)(
System out printlll(aVector elementAt(i)toStringO);
} |Vector aVector= …:
int length=aVector size();
for(int i=0;i<length;i++)f
System out println(aVector elememAt(i)toStringO);
) |import java.util.vector;
public class dic {
public void addobjects (object[] o) {
// if length > 10, vector needs to expand
for (int i = 0; i< o.length;i++) {
v.add(o); // capacity before it can add more elements.
}
}
public vector v = new vector(); // no initialcapacity.
} |<span style="WHITE-SPACE: pre"> </span><span style="font-size:14px;">更正: 自己设定初始大小。 </span> |public vector v = new vector(20);
public hashtable hash = new hashtable(10); |public class pcts {
private void method(string s) {
if (s.startswith("a")) { // violation
// …
}
}
} |public class pcts {
private void method(string s) {
if ('a' == s.charat(0)) {
// …
}
}
} |public class str {
public void method(string s) {
string string = s + "d" // violation.
string = "abc" + "d" // violation.
}
} |public class str {
public void method(string s) {
string string = s + 'd'
string = "abc" + 'd'
}
} |public class ueq {
boolean method (string string) {
return string.endswith ("a") == true; // violation
}
} |class ueq_fixed {
boolean method (string string) {
return string.endswith ("a");
}
} |public class usc {
string method () {
stringbuffer s = new stringbuffer ("hello");
string t = s + "world!";
return t;
}
} |public class ust {
void parsestring(string string) {
int index = 0;
while ((index = string.indexof(".", index)) != -1) {
system.out.println (string.substring(index, string.length()));
}
}
} |public class if {
public int method(boolean isdone) {
if (isdone) {
return 0;
} else {
return 10;
}


1
2
3
4
5
6
1 void method2(boolean istrue) {  
2    if (istrue) {  
3        _value = 0;  
4    } else {  
5        _value = 1;  
6

<span style="WHITE-SPACE: pre"> </span>}
}
} |public class if {
public int method(boolean isdone) {
return (isdone ? 0 : 10);
}


1
2
3
1void method(boolean istrue) {  
2&lt;span style=&quot;WHITE-SPACE: pre&quot;&gt; &lt;/span&gt;_value = (istrue ? 0 : 1);       // comp  
3

<span style="WHITE-SPACE: pre"> </span>}
private int _value = 0;

} |import java.util.vector;
public class loop {
void method (vector v) {
for (int i=0;i < v.size();i++) {
object o = new object();
o = v.elementat(i);
}
}
} |import java.util.vector;
public class loop {
void method (vector v) {
object o;
for (int i=0;i<v.size();i++) {
o = v.elementat(i);
}
}
} |public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(); // violation
buffer.append ("hello");
}
} |public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(max);
buffer.append ("hello");
}
private final int max = 100;
} |public class dun {
boolean method (boolean a, boolean b) {
if (!a)
return !a;
else
return !b;
}
} |public class insof {
private void method (object o) {
if (o instanceof interfacebase) { } // better
if (o instanceof classbase) { } // worse.
}
}

class classbase {}
interface interfacebase {} |String str="abc";
if(i==1){ list.add(str);} |if(i==1){String str="abc"; list.add(str);} |Map<String, String[]> paraMap = new HashMap<String, String[]>();
for( Entry<String, String[]> entry : paraMap.entrySet() )
{
String appFieldDefId = entry.getKey();
String[] values = entry.getValue();
} |
| public static Credit getNewCredit()
{
return new Credit();
} | | | | | | |
| private static Credit BaseCredit = new Credit();
public static Credit getNewCredit()
{
return (Credit)BaseCredit.clone();
} | | | | | | |
| public class usv {
void getsum (int[] values) {
for (int i=0; i < value.length; i++) {
_sum += value[i]; // violation.
}
}
void getsum2 (int[] values) {
for (int i=0; i < value.length; i++) {
_staticsum += value[i];
}
}
private int _sum;
private static int _staticsum;
} | | | | | | |
| void getsum (int[] values) {
int sum = _sum; // temporary local variable.
for (int i=0; i < value.length; i++) {
sum += value[i];
}
_sum = sum; | | | | | | |
| class maf {
public void setsize (int size) {
_size = size;
}
private int _size;
} | | | | | | |
| class daf_fixed {
final public void setsize (int size) {
_size = size;
}
private int _size;
} | | | | | | |
| public class uiso {
public uiso () {}
}
class dog extends uiso {
void method (dog dog, uiso u) {
dog d = dog;
if (d instanceof uiso) // always true.
system.out.println("dog is a uiso");
uiso uiso = u;
if (uiso instanceof object) // always true.
system.out.println("uiso is an object");
}
} | | | | | | |
| class dog extends uiso {
void method () {
dog d;
system.out.println ("dog is an uiso");
system.out.println ("uiso is an uiso");
}
} | | | | | | |
| class unc {
string _id = "unc";
}
class dog extends unc {
void method () {
dog dog = new dog ();
unc animal = (unc)dog; // not necessary.
object o = (object)dog; // not necessary.
}
} | | | | | | |
| class dog extends unc {
void method () {
dog dog = new dog();
unc animal = dog;
object o = dog;
}
} | | | | | | |
| import java.io.*;
public class cs {
public static void main (string args[]) {
cs cs = new cs ();
cs.method ();
}
public void method () {
try {
fileinputstream fis = new fileinputstream ("cs.java");
int count = 0;
while (fis.read () != -1)
count++;
system.out.println (count);
fis.close ();
} catch (filenotfoundexception e1) {
} catch (ioexception e2) {
}
}
} | | | | | | |
| import java.io.fileinputstream;
public class try {
void method (fileinputstream fis) {
for (int i = 0; i < size; i++) {
try { // violation
_sum += fis.read();
} catch (exception e) {}
}
}
private int _sum;
} | | | | | | |
| void method (fileinputstream fis) {
try {
for (int i = 0; i < size; i++) { _sum += fis.read();
}
} catch (exception e) {}
} | | | | | | |
| import java.util.vector;
public class syn {
public synchronized void method (object o) {
}
private void test () {
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i)); // violation
}
}
private vector vector = new vector (5, 5);
} | | | | | | |
| import java.util.vector;
public class syn {
public void method (object o) {
}
private void test () {
synchronized{//在一个同步块中执行非同步方法
for (int i = 0; i < vector.size(); i++) {
method (vector.elementat(i));
}
}
}
private vector vector = new vector (5, 5);
} | | | | | | |
| public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a / 4; // should be replaced with "a >> 2".
int div2 = a / 8; // should be replaced with "a >> 3".
int temp = a / 3;
int mul = a * 4; // should be replaced with "a << 2".
int mul2 = 8 * a; // should be replaced with "a << 3".
int temp2 = a * 3;
}
} | | | | | | |
| public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a >> 2;
int div2 = a >> 3;
int temp = a / 3; // 不能转换成位移操作
int mul = a << 2;
int mul2 = a << 3;
int temp = a * 3; // 不能转换
}
} | | | | | | |
| public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
for (int i = 0; i < array2.length; i++) {
array2 [i] = array1 [i]; // violation
}
}
} | | | | | | |
| public class irb
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
system.arraycopy(array1, 0, array2, 0, 100);
}
} | | | | | | |
| Vector aVector= …;
for(int i=0;i<aVector size();i++)(
System out printlll(aVector elementAt(i)toStringO);
} | | | | | | |
| Vector aVector= …:
int length=aVector size();
for(int i=0;i<length;i++)f
System out println(aVector elememAt(i)toStringO);
) | | | | | | |
| import java.util.vector;
public class dic {
public void addobjects (object[] o) {
// if length > 10, vector needs to expand
for (int i = 0; i< o.length;i++) {
v.add(o); // capacity before it can add more elements.
}
}
public vector v = new vector(); // no initialcapacity.
} | | | | | | |
| <span style="WHITE-SPACE: pre"> </span><span style="font-size:14px;">更正: 自己设定初始大小。 </span> | | | | | | |
| public vector v = new vector(20);
public hashtable hash = new hashtable(10); | | | | | | |
| public class pcts {
private void method(string s) {
if (s.startswith("a")) { // violation
// …
}
}
} | | | | | | |
| public class pcts {
private void method(string s) {
if ('a' == s.charat(0)) {
// …
}
}
} | | | | | | |
| public class str {
public void method(string s) {
string string = s + "d" // violation.
string = "abc" + "d" // violation.
}
} | | | | | | |
| public class str {
public void method(string s) {
string string = s + 'd'
string = "abc" + 'd'
}
} | | | | | | |
| public class ueq {
boolean method (string string) {
return string.endswith ("a") == true; // violation
}
} | | | | | | |
| class ueq_fixed {
boolean method (string string) {
return string.endswith ("a");
}
} | | | | | | |
| public class usc {
string method () {
stringbuffer s = new stringbuffer ("hello");
string t = s + "world!";
return t;
}
} | | | | | | |
| public class ust {
void parsestring(string string) {
int index = 0;
while ((index = string.indexof(".", index)) != -1) {
system.out.println (string.substring(index, string.length()));
}
}
} | | | | | | |
| public class if {
public int method(boolean isdone) {
if (isdone) {
return 0;
} else {
return 10;
}


1
2
3
4
5
6
1 void method2(boolean istrue) {  
2    if (istrue) {  
3        _value = 0;  
4    } else {  
5        _value = 1;  
6

<span style="WHITE-SPACE: pre"> </span>}
}
} | | | | | | |
| public class if {
public int method(boolean isdone) {
return (isdone ? 0 : 10);
}


1
2
3
1void method(boolean istrue) {  
2&lt;span style=&quot;WHITE-SPACE: pre&quot;&gt; &lt;/span&gt;_value = (istrue ? 0 : 1);       // comp  
3

<span style="WHITE-SPACE: pre"> </span>}
private int _value = 0;

} | | | | | | |
| import java.util.vector;
public class loop {
void method (vector v) {
for (int i=0;i < v.size();i++) {
object o = new object();
o = v.elementat(i);
}
}
} | | | | | | |
| import java.util.vector;
public class loop {
void method (vector v) {
object o;
for (int i=0;i<v.size();i++) {
o = v.elementat(i);
}
}
} | | | | | | |
| public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(); // violation
buffer.append ("hello");
}
} | | | | | | |
| public class rsbc {
void method () {
stringbuffer buffer = new stringbuffer(max);
buffer.append ("hello");
}
private final int max = 100;
} | | | | | | |
| public class dun {
boolean method (boolean a, boolean b) {
if (!a)
return !a;
else
return !b;
}
} | | | | | | |
| public class insof {
private void method (object o) {
if (o instanceof interfacebase) { } // better
if (o instanceof classbase) { } // worse.
}
}

class classbase {}
interface interfacebase {} | | | | | | |
| String str="abc";
if(i==1){ list.add(str);} | | | | | | |
| if(i==1){String str="abc"; list.add(str);} | | | | | | |
| Map<String, String[]> paraMap = new HashMap<String, String[]>();
for( Entry<String, String[]> entry : paraMap.entrySet() )
{
String appFieldDefId = entry.getKey();
String[] values = entry.getValue();
} | | | | | | |

1
1

给TA打赏
共{{data.count}}人
人已打赏
安全技术

bootstrap栅格系统自定义列

2021-12-21 16:36:11

安全技术

从零搭建自己的SpringBoot后台框架(二十三)

2022-1-12 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索