Java 代码性能优化

代码优化,一个很重要的课题。可能有些人觉得没用,一些细小的地方有什么好修改的,改与不改对于代码的运行效率有什么影响呢?这个问题我是这么考虑的,就像大海里面的鲸鱼一样,它吃一条小虾米有用吗?没用,但是,吃的小虾米一多之后,鲸鱼就被喂饱了。代码优化也是一样,如果项目着眼于尽快无BUG上线,那么此时可以抓大放小,代码的细节可以不精打细磨;但是如果有足够的时间开发、维护代码,这时候就必须考虑每个可以优化的细节了,一个一个细小的优化点累积起来,对于代码的运行效率绝对是有提升的。

代码优化的目标是:

1、减小代码的体积

2、提高代码运行的效率

代码优化细节

1、尽量指定类、方法的final修饰符

带有final修饰符的类是不可派生的。在Java核心API中,有许多应用final的例子,例如java.lang.String,整个类都是final的。为类指定final修饰符可以让类不可以被继承,为方法指定final修饰符可以让方法不可以被重写。如果指定了一个类为final,则该类所有的方法都是final的。Java编译器会寻找机会内联所有的final方法,内联对于提升Java运行效率作用重大,具体参见Java运行期优化。此举能够使性能平均提高50%。

2、尽量重用对象

特别是String对象的使用,出现字符串连接时应该使用StringBuilder/StringBuffer代替。由于Java虚拟机不仅要花时间生成对象,以后可能还需要花时间对这些对象进行垃圾回收和处理,因此,生成过多的对象将会给程序的性能带来很大的影响。

3、尽可能使用局部变量

调用方法时传递的参数以及在调用中创建的临时变量都保存在栈中速度较快,其他变量,如静态变量、实例变量等,都在堆中创建,速度较慢。另外,栈中创建的变量,随着方法的运行结束,这些内容就没了,不需要额外的垃圾回收。

4、及时关闭流

Java编程过程中,进行数据库连接、I/O流操作时务必小心,在使用完毕后,及时关闭以释放资源。因为对这些大对象的操作会造成系统大的开销,稍有不慎,将会导致严重的后果。

5、尽量减少对变量的重复计算

明确一个概念,对方法的调用,即使方法中只有一句语句,也是有消耗的,包括创建栈帧、调用方法时保护现场、调用方法完毕时恢复现场等。所以例如下面的操作:

<code class=" hljs r" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (int i = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; i < list.size(); i++){<span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span>}</code>

建议替换为:

<code class=" hljs r" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (int i = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>, int length = list.size(); i < length; i++){<span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span>}</code>

这样,在list.size()很大的时候,就减少了很多的消耗

6、尽量采用懒加载的策略,即在需要的时候才创建

例如:

<code class=" hljs rust" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;">String <span class="hljs-keyword" style="color: rgb(0, 0, 136);">str</span> = <span class="hljs-string" style="color: rgb(0, 136, 0);">"aaa"</span>;<span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (i == <span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>)
{list.add(<span class="hljs-keyword" style="color: rgb(0, 0, 136);">str</span>);}</code>

建议替换为:

<code class=" hljs rust" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (i == <span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>)
{String <span class="hljs-keyword" style="color: rgb(0, 0, 136);">str</span> = <span class="hljs-string" style="color: rgb(0, 136, 0);">"aaa"</span>;list.add(<span class="hljs-keyword" style="color: rgb(0, 0, 136);">str</span>);}</code>

7、慎用异常

异常对性能不利。抛出异常首先要创建一个新的对象,Throwable接口的构造函数调用名为fillInStackTrace()的本地同步方法,fillInStackTrace()方法检查堆栈,收集调用跟踪信息。只要有异常被抛出,Java虚拟机就必须调整调用堆栈,因为在处理过程中创建了一个新的对象。异常只能用于错误处理,不应该用来控制程序流程。

8、不要在循环中使用try…catch…,应该把其放在最外层

除非不得已。如果毫无理由地这么写了,只要你的领导资深一点、有强迫症一点,八成就要骂你为什么写出这种垃圾代码来了

9、如果能估计到待添加的内容长度,为底层以数组方式实现的集合、工具类指定初始长度

比如ArrayList、LinkedLlist、StringBuilder、StringBuffer、HashMap、HashSet等等,以StringBuilder为例:

(1)StringBuilder()      // 默认分配16个字符的空间

(2)StringBuilder(int size)  // 默认分配size个字符的空间

(3)StringBuilder(String str) // 默认分配16个字符+str.length()个字符空间

可以通过类(这里指的不仅仅是上面的StringBuilder)的来设定它的初始化容量,这样可以明显地提升性能。比如StringBuilder吧,length表示当前的StringBuilder能保持的字符数量。因为当StringBuilder达到最大容量的时候,它会将自身容量增加到当前的2倍再加2,无论何时只要StringBuilder达到它的最大容量,它就不得不创建一个新的字符数组然后将旧的字符数组内容拷贝到新字符数组中—-这是十分耗费性能的一个操作。试想,如果能预估到字符数组中大概要存放5000个字符而不指定长度,最接近5000的2次幂是4096,每次扩容加的2不管,那么:

(1)在4096 的基础上,再申请8194个大小的字符数组,加起来相当于一次申请了12290个大小的字符数组,如果一开始能指定5000个大小的字符数组,就节省了一倍以上的空间

(2)把原来的4096个字符拷贝到新的的字符数组中去

这样,既浪费内存空间又降低代码运行效率。所以,给底层以数组实现的集合、工具类设置一个合理的初始化容量是错不了的,这会带来立竿见影的效果。但是,注意,像HashMap这种是以数组+链表实现的集合,别把初始大小和你估计的大小设置得一样,因为一个table上只连接一个对象的可能性几乎为0。初始大小建议设置为2的N次幂,如果能估计到有2000个元素,设置成new HashMap(128)、new HashMap(256)都可以。

10、当复制大量数据时,使用System.arraycopy()命令

11、乘法和除法使用移位操作

例如:

<code class=" hljs fsharp" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> < <span class="hljs-number" style="color: rgb(0, 102, 102);">100000</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> += <span class="hljs-number" style="color: rgb(0, 102, 102);">5</span>){a = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> * <span class="hljs-number" style="color: rgb(0, 102, 102);">8</span>;b = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> / <span class="hljs-number" style="color: rgb(0, 102, 102);">2</span>;}</code>

用移位操作可以极大地提高性能,因为在计算机底层,对位的操作是最方便、最快的,因此建议修改为:

<code class=" hljs fsharp" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> < <span class="hljs-number" style="color: rgb(0, 102, 102);">100000</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> += <span class="hljs-number" style="color: rgb(0, 102, 102);">5</span>){a = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> << <span class="hljs-number" style="color: rgb(0, 102, 102);">3</span>;b = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">val</span> >> <span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>;}</code>

移位操作虽然快,但是可能会使代码不太好理解,因此最好加上相应的注释。

12、循环内不要不断创建对象引用

例如:

<code class=" hljs vala" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> i = <span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>; i <= count; i++){<span class="hljs-built_in" style="color: rgb(102, 0, 102);">Object</span> obj = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">new</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">Object</span>();}</code>

这种做法会导致内存中有count份Object对象引用存在,count很大的话,就耗费内存了,建议为改为:

<code class=" hljs vala" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-built_in" style="color: rgb(102, 0, 102);">Object</span> obj = <span class="hljs-literal" style="color: rgb(0, 102, 102);">null</span>;<span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> i = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; i <= count; i++) { obj = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">new</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">Object</span>(); }</code>

这样的话,内存中只有一份Object对象引用,每次new Object()的时候,Object对象引用指向不同的Object罢了,但是内存中只有一份,这样就大大节省了内存空间了。

13、基于效率和类型检查的考虑,应该尽可能使用array,无法确定数组大小时才使用ArrayList

14、尽量使用HashMap、ArrayList、StringBuilder,除非线程安全需要,否则不推荐使用Hashtable、Vector、StringBuffer,后三者由于使用同步机制而导致了性能开销

15、不要将数组声明为public static final

因为这毫无意义,这样只是定义了引用为static final,数组的内容还是可以随意改变的,将数组声明为public更是一个安全漏洞,这意味着这个数组可以被外部类所改变

16、尽量在合适的场合使用单例

使用单例可以减轻加载的负担、缩短加载的时间、提高加载的效率,但并不是所有地方都适用于单例,简单来说,单例主要适用于以下三个方面:

(1)控制资源的使用,通过线程同步来控制资源的并发访问

(2)控制实例的产生,以达到节约资源的目的

(3)控制数据的共享,在不建立直接关联的条件下,让多个不相关的进程或线程之间实现通信

17、尽量避免随意使用静态变量

要知道,当某个对象被定义为static的变量所引用,那么gc通常是不会回收这个对象所占有的堆内存的,如:

<code class=" hljs cs" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">public</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">class</span> A
{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">private</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">static</span> B b = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">new</span> B();}</code>

此时静态变量b的生命周期与A类相同,如果A类不被卸载,那么引用B指向的B对象会常驻内存,直到程序终止

18、及时清除不再需要的会话

为了清除不再活动的会话,许多应用服务器都有默认的会话超时时间,一般为30分钟。当应用服务器需要保存更多的会话时,如果内存不足,那么操作系统会把部分数据转移到磁盘,应用服务器也可能根据MRU(最近最频繁使用)算法把部分不活跃的会话转储到磁盘,甚至可能抛出内存不足的异常。如果会话要被转储到磁盘,那么必须要先被序列化,在大规模集群中,对对象进行序列化的代价是很昂贵的。因此,当会话不再需要时,应当及时调用HttpSession的invalidate()方法清除会话。

19、实现RandomAccess接口的集合比如ArrayList,应当使用最普通的for循环而不是foreach循环来遍历

这是JDK推荐给用户的。JDK API对于RandomAccess接口的解释是:实现RandomAccess接口用来表明其支持快速随机访问,此接口的主要目的是允许一般的算法更改其行为,从而将其应用到随机或连续访问列表时能提供良好的性能。实际经验表明,实现RandomAccess接口的类实例,假如是随机访问的,使用普通for循环效率将高于使用foreach循环;反过来,如果是顺序访问的,则使用Iterator会效率更高。可以使用类似如下的代码作判断:

<code class=" hljs php" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">list</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">instanceof</span> RandomAccess){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (int i = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; i < <span class="hljs-keyword" style="color: rgb(0, 0, 136);">list</span>.size(); i++){}}<span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span>{Iterator<span class="hljs-preprocessor" style="color: rgb(68, 68, 68);"><?</span>> iterator = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">list</span>.iterable(); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">while</span> (iterator.hasNext()){iterator.next()}}</code>

foreach循环的底层实现原理就是迭代器Iterator,参见Java语法糖1:可变长度参数以及foreach循环原理。所以后半句”反过来,如果是顺序访问的,则使用Iterator会效率更高”的意思就是顺序访问的那些类实例,使用foreach循环去遍历。

20、使用同步代码块替代同步方法

这点在多线程模块中的synchronized锁方法块一文中已经讲得很清楚了,除非能确定一整个方法都是需要进行同步的,否则尽量使用同步代码块,避免对那些不需要进行同步的代码也进行了同步,影响了代码执行效率。

21、将常量声明为static final,并以大写命名

这样在编译期间就可以把这些内容放入常量池中,避免运行期间计算生成常量的值。另外,将常量的名字以大写命名也可以方便区分出常量与变量

22、不要创建一些不使用的对象,不要导入一些不使用的类

这毫无意义,如果代码中出现”The value of the local variable i is not used”、”The import java.util is never used”,那么请删除这些无用的内容

23、程序运行过程中避免使用反射

关于,请参见反射。反射是Java提供给用户一个很强大的功能,功能强大往往意味着效率不高。不建议在程序运行过程中使用尤其是频繁使用反射机制,特别是Method的invoke方法,如果确实有必要,一种建议性的做法是将那些需要通过反射加载的类在项目启动的时候通过反射实例化出一个对象并放入内存—-用户只关心和对端交互的时候获取最快的响应速度,并不关心对端的项目启动花多久时间。

24、使用数据库连接池和线程池

这两个池都是用于重用对象的,前者可以避免频繁地打开和关闭连接,后者可以避免频繁地创建和销毁线程

25、使用带缓冲的输入输出流进行IO操作

带缓冲的输入输出流,即BufferedReader、BufferedWriter、BufferedInputStream、BufferedOutputStream,这可以极大地提升IO效率

26、顺序插入和随机访问比较多的场景使用ArrayList,元素删除和中间插入比较多的场景使用LinkedList

这个,理解ArrayList和LinkedList的原理就知道了

27、不要让public方法中有太多的形参

public方法即对外提供的方法,如果给这些方法太多形参的话主要有两点坏处:

1、违反了面向对象的编程思想,Java讲求一切都是对象,太多的形参,和面向对象的编程思想并不契合

2、参数太多势必导致方法调用的出错概率增加

至于这个”太多”指的是多少个,3、4个吧。比如我们用JDBC写一个insertStudentInfo方法,有10个学生信息字段要插如Student表中,可以把这10个参数封装在一个实体类中,作为insert方法的形参

28、字符串变量和字符串常量equals的时候将字符串常量写在前面

这是一个比较常见的小技巧了,如果有以下代码:

<code class=" hljs r" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;">String str = <span class="hljs-string" style="color: rgb(0, 136, 0);">"123"</span>;
<span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (str.equals(<span class="hljs-string" style="color: rgb(0, 136, 0);">"123"</span>)) {<span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span>}</code>

建议修改为:

<code class=" hljs r" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;">String str = <span class="hljs-string" style="color: rgb(0, 136, 0);">"123"</span>;
<span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (<span class="hljs-string" style="color: rgb(0, 136, 0);">"123"</span>.equals(str)){<span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span>}</code>

这么做主要是可以避免空指针异常

29、请知道,在java中if (i == 1)和if (1 == i)是没有区别的,但从阅读习惯上讲,建议使用前者

平时有人问,”if (i == 1)”和”if (1== i)”有没有区别,这就要从C/C++讲起。

在C/C++中,”if (i == 1)”判断条件成立,是以0与非0为基准的,0表示false,非0表示true,如果有这么一段代码:

<code class=" hljs r" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;">int i = <span class="hljs-number" style="color: rgb(0, 102, 102);">2</span>;
<span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (i == <span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>){<span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span>}<span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span>{<span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span>}</code>

C/C++判断”i==1″不成立,所以以0表示,即false。但是如果:

<code class=" hljs r" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;">int i = <span class="hljs-number" style="color: rgb(0, 102, 102);">2</span>;<span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (i = <span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span> }<span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span>{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span> }</code>

万一程序员一个不小心,把”if (i == 1)”写成”if (i = 1)”,这样就有问题了。在if之内将i赋值为1,if判断里面的内容非0,返回的就是true了,但是明明i为2,比较的值是1,应该返回的false。这种情况在C/C++的开发中是很可能发生的并且会导致一些难以理解的错误产生,所以,为了避免开发者在if语句中不正确的赋值操作,建议将if语句写为:

<code class=" hljs r" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;">int i = <span class="hljs-number" style="color: rgb(0, 102, 102);">2</span>;<span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (<span class="hljs-number" style="color: rgb(0, 102, 102);">1</span> == i) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span> }<span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span>{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span> }</code>

这样,即使开发者不小心写成了”1 = i”,C/C++编译器也可以第一时间检查出来,因为我们可以对一个变量赋值i为1,但是不能对一个常量赋值1为i。

但是,在Java中,C/C++这种”if (i = 1)”的语法是不可能出现的,因为一旦写了这种语法,Java就会编译报错”Type mismatch: cannot convert from int to boolean”。但是,尽管Java的”if (i == 1)”和”if (1 == i)”在语义上没有任何区别,但是从阅读习惯上讲,建议使用前者会更好些。

30、不要对数组使用toString()方法

看一下对数组使用toString()打印出来的是什么:

<code class=" hljs cs" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">public</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">void</span> <span class="hljs-title">main</span>(String[] args){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span>[] <span class="hljs-keyword" style="color: rgb(0, 0, 136);">is</span> = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">new</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span>[]{<span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">2</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">3</span>};System.<span class="hljs-keyword" style="color: rgb(0, 0, 136);">out</span>.println(<span class="hljs-keyword" style="color: rgb(0, 0, 136);">is</span>.toString());}</code>

结果是:

<code class=" hljs ruby" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;">[<span class="hljs-constant">I</span><span class="hljs-variable" style="color: rgb(102, 0, 102);">@18a992f</span></code>

本意是想打印出数组内容,却有可能因为数组引用is为空而导致空指针异常。不过虽然对数组toString()没有意义,但是对集合toString()是可以打印出集合里面的内容的,因为集合的父类AbstractCollections重写了Object的toString()方法。

31、不要对超出范围的基本数据类型做向下强制转型

这绝不会得到想要的结果:

<code class=" hljs cs" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">public</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">void</span> <span class="hljs-title">main</span>(String[] args)
{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">long</span> l = <span class="hljs-number" style="color: rgb(0, 102, 102);">12345678901234</span>L;<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> i = (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span>)l;System.<span class="hljs-keyword" style="color: rgb(0, 0, 136);">out</span>.println(i);}</code>

我们可能期望得到其中的某几位,但是结果却是:

1942892530

解释一下。Java中long是8个字节64位的,所以12345678901234在计算机中的表示应该是:

0000 0000 0000 0000 0000 1011 0011 1010 0111 0011 1100 1110 0010 1111 1111 0010

一个int型数据是4个字节32位的,从低位取出上面这串二进制数据的前32位是:

0111 0011 1100 1110 0010 1111 1111 0010

这串二进制表示为十进制1942892530,所以就是我们上面的控制台上输出的内容。从这个例子上还能顺便得到两个结论:

1、整型默认的数据类型是int,long l = 12345678901234L,这个数字已经超出了int的范围了,所以最后有一个L,表示这是一个long型数。顺便,浮点型的默认类型是double,所以定义float的时候要写成””float f = 3.5f”

2、接下来再写一句”int ii = l + i;”会报错,因为long + int是一个long,不能赋值给int

32、公用的集合类中不使用的数据一定要及时remove掉

如果一个集合类是公用的(也就是说不是方法里面的属性),那么这个集合里面的元素是不会自动释放的,因为始终有引用指向它们。所以,如果公用集合里面的某些数据不使用而不去remove掉它们,那么将会造成这个公用集合不断增大,使得系统有内存泄露的隐患。

33、把一个基本数据类型转为字符串,基本数据类型.toString()是最快的方式、String.valueOf(数据)次之、数据+””最慢

把一个基本数据类型转为一般有三种方式,我有一个Integer型数据i,可以使用i.toString()、String.valueOf(i)、i+””三种方式,三种方式的效率如何,看一个测试:

<code class=" hljs cs" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">public</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">void</span> <span class="hljs-title">main</span>(String[] args){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> loopTime = <span class="hljs-number" style="color: rgb(0, 102, 102);">50000</span>;Integer i = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">long</span> startTime = System.currentTimeMillis(); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> j = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; j < loopTime; j++){String str = String.valueOf(i);}System.<span class="hljs-keyword" style="color: rgb(0, 0, 136);">out</span>.println(<span class="hljs-string" style="color: rgb(0, 136, 0);">"String.valueOf():"</span> + (System.currentTimeMillis() - startTime) + <span class="hljs-string" style="color: rgb(0, 136, 0);">"ms"</span>);startTime = System.currentTimeMillis(); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> j = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; j < loopTime; j++){String str = i.toString();}System.<span class="hljs-keyword" style="color: rgb(0, 0, 136);">out</span>.println(<span class="hljs-string" style="color: rgb(0, 136, 0);">"Integer.toString():"</span> + (System.currentTimeMillis() - startTime) + <span class="hljs-string" style="color: rgb(0, 136, 0);">"ms"</span>);startTime = System.currentTimeMillis(); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> j = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; j < loopTime; j++){String str = i + <span class="hljs-string" style="color: rgb(0, 136, 0);">""</span>;}System.<span class="hljs-keyword" style="color: rgb(0, 0, 136);">out</span>.println(<span class="hljs-string" style="color: rgb(0, 136, 0);">"i + \"\":"</span> + (System.currentTimeMillis() - startTime) + <span class="hljs-string" style="color: rgb(0, 136, 0);">"ms"</span>);}</code>

运行结果为:

<code class=" hljs mathematica" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">String</span>.valueOf():<span class="hljs-number" style="color: rgb(0, 102, 102);">11</span>ms <span class="hljs-keyword" style="color: rgb(0, 0, 136);">Integer</span>.toString():<span class="hljs-number" style="color: rgb(0, 102, 102);">5</span>ms i + <span class="hljs-string" style="color: rgb(0, 136, 0);">""</span>:<span class="hljs-number" style="color: rgb(0, 102, 102);">25</span>ms</code>

所以以后遇到把一个基本数据类型转为String的时候,优先考虑使用toString()方法。至于为什么,很简单:

1、String.valueOf()方法底层调用了Integer.toString()方法,但是会在调用前做空判断

2、Integer.toString()方法就不说了,直接调用了

3、i + “”底层使用了StringBuilder实现,先用append方法拼接,再用toString()方法获取字符串

三者对比下来,明显是2最快、1次之、3最慢

34、使用最有效率的方式去遍历Map

遍历Map的方式有很多,通常场景下我们需要的是遍历Map中的Key和Value,那么推荐使用的、效率最高的方式是:

<code class=" hljs vbscript" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">public</span> static void main(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>[] args){HashMap<<span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>, <span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>> hm = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">new</span> HashMap<<span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>, <span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>>();hm.put(<span class="hljs-string" style="color: rgb(0, 136, 0);">"111"</span>, <span class="hljs-string" style="color: rgb(0, 136, 0);">"222"</span>);<span class="hljs-keyword" style="color: rgb(0, 0, 136);">Set</span><Map.Entry<<span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>, <span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>>> entrySet = hm.entrySet();Iterator<Map.Entry<<span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>, <span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>>> iter = entrySet.iterator(); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">while</span> (iter.hasNext()){Map.Entry<<span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>, <span class="hljs-built_in" style="color: rgb(102, 0, 102);">String</span>> entry = iter.<span class="hljs-keyword" style="color: rgb(0, 0, 136);">next</span>();System.out.println(entry.getKey() + <span class="hljs-string" style="color: rgb(0, 136, 0);">"\t"</span> + entry.getValue());}}</code>

如果你只是想遍历一下这个Map的key值,那用”Set keySet = hm.keySet();”会比较合适一些

35、对资源的close()建议分开操作

意思是,比如我有这么一段代码:

<code class=" hljs r" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">try</span>{XXX.close();YYY.close();}catch (Exception e){<span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span>}</code>

建议修改为:

<code class=" hljs r" style="display: block; padding: 0px; background: transparent; color: inherit; font-family: "Source Code Pro", monospace;"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">try</span>{ XXX.close(); }catch (Exception e) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span> }<span class="hljs-keyword" style="color: rgb(0, 0, 136);">try</span>{ YYY.close(); }catch (Exception e) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">...</span> }</code>

虽然有些麻烦,却能避免资源泄露。我想,如果没有修改过的代码,万一XXX.close()抛异常了,那么就进入了cath块中了,YYY.close()不会执行,YYY这块资源就不会回收了,一直占用着,这样的代码一多,是可能引起资源句柄泄露的。而改为上面的写法之后,就保证了无论如何XXX和YYY都会被close掉。


转自http://blog.csdn.net/richard_jason/article/details/53004974

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/443344.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

20个常用的正则表达式

正则表达式——古老而又强大的文本处理工具。仅用一段简短的表达式语句&#xff0c;就能快速地实现一个复杂的业务逻辑。掌握正则表达式&#xff0c;让你的开发效率有一个质的飞跃。 正则表达式经常被用于字段或任意字符串的校验&#xff0c;比如下面这段校验基本日期格式的Jav…

Mysql处理海量数据时的一些优化查询速度方法

由于在参与的实际项目中发现当mysql表的数据量达到百万级时&#xff0c;普通SQL查询效率呈直线下降&#xff0c;而且如果where中的查询条件较多时&#xff0c;其查询速度简直无法容忍。曾经测试对一个包含400多万条记录&#xff08;有索引&#xff09;的表执行一条条件查询&…

八大排序算法的Python实现

1、插入排序 描述 插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中&#xff0c;从而得到一个新的、个数加一的有序数据&#xff0c;算法适用于少量数据的排序&#xff0c;时间复杂度为O(n^2)。是稳定的排序方法。插入算法把要排序的数组分成两部分&#xff1a;第…

重定向和请求转发的区别

一次重定向的过程 我的代码里面已经写好了&#xff0c;redirectAndFoward.jsp页面上有一个表单&#xff0c;表单重定向到redirectAndFowardTarget.jsp&#xff0c;那么这一次的重定向过程为&#xff1a; 1、以指定方式&#xff08;表单看method&#xff0c;直接URL发起就是GE…

hibernate映射关系的配置

XML文件个人书写规范 <!-- users属性&#xff0c;本类与User的一对多关系 --> 格式&#xff1a;&#xff1f;属性&#xff0c;本类与&#xff1f;的&#xff1f; ?1 属性名 ?2 关联对类型 ?3 关系配置模板 多对一&#xff1a; <many-to-one name…

公司创始人、董事长、CEO和总裁谁更大,有什么区别?

创始人 英文称Founder&#xff0c;创始人是一个企业&#xff0c;社团&#xff0c;基金、组织&#xff0c;网站等的发起和创立人。任正非是华为的创始人。如果公司一开始就有多个人就叫联合创始人。比如腾讯有马化腾张志东等5位联合创始人&#xff0c;阿里巴巴则有马云、张英等1…

JQuery中的一些重要方法

选择上一级元素 parent(expr) 选择所有上级元素(前辈) parents(expr) 选择下一级元素 children(expr) 选择所有后代元素 find(expr) 选择同级元素(兄弟) siblings(expr) 选择兄元素(前一个) prev( expr ) 选…

各种数据库分页查询sql语句

1.oracle数据库分页 select * from (select a.*,rownum rc from 表名 where rownum<endrow) a where a.rc>startrow; 2.DB2数据库分页 Select * from (select rownumber() over() as rc,a.* from (select * from 表名 order by 列名) as a) …

Java线程面试题 Top 53

1) 什么是线程&#xff1f; 线程是操作系统能够进行运算调度的最小单位&#xff0c;它被包含在进程之中&#xff0c;是进程中的实际运作单位。程序员可以通过它进行多处理器编程&#xff0c;你可以使用多线程对运算密集型任务提速。比如&#xff0c;如果一个线程完成一个任务要…

EL表达式的11个内置对象

EL是JSP内置的表达式语言 JSP2.0开始&#xff0c;不让再使用Java脚本&#xff0c;而是使用EL表达式和动态标签来代替Java脚本 EL替代的是<%... %>&#xff0c;也就是说EL只能做输出 EL可以输出的东西都在11个内置对象中&#xff0c;11个内置对象&#xff0c;其中10个是…

xml的约束

为什么需要约束&#xff1f; 比如现在定义一个person的xml文件&#xff0c;只想要这个文件里面保存人的信息&#xff0c;比如name age等&#xff0c;但是如果在xml文件中写了一个标签<猫>&#xff0c;发现可以正常显示&#xff0c;因为符合语法规范。但是猫肯定不…

会话跟踪技术之Cookie

1 Cookie概述 1.1 什么叫Cookie Cookie翻译成中文是小甜点&#xff0c;小饼干的意思。在HTTP中它表示服务器送给客户端浏览器的小甜点。其实Cookie就是一个键和一个值构成的&#xff0c;随着服务器端的响应发送给客户端浏览器。然后客户端浏览器会把Cookie保存起来&#xff…

会话跟踪技术之HttpSession

1 HttpSession概述 1.1 什么是HttpSesssion javax.servlet.http.HttpSession接口表示一个会话&#xff0c;我们可以把一个会话内需要共享的数据保存到HttSession对象中&#xff01; 1.2 获取HttpSession对象 HttpSession request.getSesssion()&#xff1a;如果当前会话已…

Spring MVC 中 HandlerInterceptorAdapter的使用

一般情况下&#xff0c;对来自浏览器的请求的拦截&#xff0c;是利用Filter实现的&#xff0c;这种方式可以实现Bean预处理、后处理。 Spring MVC的拦截器不仅可实现Filter的所有功能&#xff0c;还可以更精确的控制拦截精度。 spring为我们提供了org.springframework.web.ser…

Nginx安装教程

1 nginx安装环境 nginx是C语言开发&#xff0c;建议在linux上运行&#xff0c;本教程使用Centos6.5作为安装环境。 --gcc 安装nginx需要先将官网下载的源码进行编译&#xff0c;编译依赖gcc环境&#xff0c;如果没有gcc环境&#xff0c;需要安装gcc&#xff1a;yum install gcc…

Maven Scope取值的含义

maven依赖关系中Scope的作用 Dependency Scope 在POM 4中&#xff0c;<dependency>中还引入了<scope>&#xff0c;它主要管理依赖的部署。目前<scope>可以使用5个值&#xff1a; * compile&#xff0c;缺省值&#xff0c;适用于所有阶段&#xff0c;会…

Solr--企业级搜索应用服务器

1. 概述 1.1.什么是Solr Solr 是Apache下的一个顶级开源项目&#xff0c;采用Java开发&#xff0c;它是基于Lucene的全文搜索服务器。Solr提供了比Lucene更为丰富的查询语言&#xff0c;同时实现了可配置、可扩展&#xff0c;并对索引、搜索性能进行了优化。 Solr可以独立运行&…

HttpClient使用详解

1. 什么是httpclient HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了&#xff0c;越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能&#xff0c;但是对于大部分应用程序来说&#x…

Nginx反向代理及负载均衡

1. nginx反向代理 1.1. 什么是反向代理 通常的代理服务器&#xff0c;只用于代理内部网络对Internet的连接请求&#xff0c;客户机必须指定代理服务器,并将本来要直接发送到Web服务器上的http请求发送到代理服务器中由代理服务器向Internet上的web服务器发起请求&#xff0c;…

SolrCloud详解及搭建

1. 什么是SolrCloud 1.1. 什么是SolrCloud SolrCloud(solr 云)是Solr提供的分布式搜索方案&#xff0c;当你需要大规模&#xff0c;容错&#xff0c;分布式索引和检索能力时使用SolrCloud。当一个系统的索引数据量少的时候是不需要使用SolrCloud的&#xff0c;当索引量很大&am…