现在的位置: 首页 > 综合 > 正文

Java性能 (1) – Java Programming Guidelines

2013年02月12日 ⁄ 综合 ⁄ 共 2362字 ⁄ 字号 评论关闭

转载地址:http://blog.csdn.net/jinhuiyu/archive/2008/12/10/3487584.aspx

这一部分包含了Java编码和性能方面的问题, 这个guidelines不是专门针对应用服务器的,但这是一些在很多情况下的偶通用的规则,如需了解Java coding最佳实践的完整分析探讨,请参考 Java Blueprints.
避免序列化(Serialization)和反序列化(Deserialization)

序列化和反序列化一个对象都是非常消耗CPU (CPU-intensive) 的过程,很有可能会减缓你的系统运行速度,使用
transient 关键字来减少数据的序列化。另外,定制(customized)你的readObject() and
writeOjbect()方法在一些情况下也会多系统性能有好处。

使用StringBuffer进行字符串运算

这一段大家都知道就不翻译了

给长时间不再用的变量赋Null值

明确的给长时间不用的对象赋Null值会帮助Java的垃圾回收器识别出这一部分的内存可以被安全的回收,虽然Java支持内存管理,但是这并避免不了内存泄漏和过分利用内存。

应用程序如果不释放对象的引用可能会带来内存泄漏, 也可能阻碍Java垃圾回收器回收这些对象造成过多的内存被占用。在用完一个对象之后明确的赋空值会让垃圾回收器更好的回收内存。

检测内存泄漏的一个方法是使用Profiling Tools在每个一Transaction运行完以后打一个内存快照(memory
snapshots), 一个没有内存泄漏的应用在稳定状态下进行垃圾回收后会显示稳定的动态内存堆(Active heap memory)。

在需要的情况下定义方法为Final

比较新的动态优化编译器能进行内部的或者程序交互的优化, 就算是Java方法没有定义成Final的时候。使用Final关键字的初衷:为了程序架构和可维护性。

除非你非常确认你的方法不能被重写才能用Final。

把常量定义成Static Final

如果你把常量定义成static final的,动态编译器能非常容易的进行一些常量折叠(constant folding)的优化。

避免Finalizers

在代码里面加finally方法会让垃圾回收更昂贵和无法预测。Java虚拟机不保证finally方法运行的时间,finally方法并不一定保证在程序退出以前被运行。

把方法的参数定义成final的

如果方法的参数在方法内部不被修改,把他们定义成final的,通常情况下把所有的变量设成final的如果他们在方法内部不被修改或者被set成什么值。

在必需的情况下再同步

不要同步你的代码段或者方法,除非这是必需的。为了避免可测性瓶颈,请保证你的同步代码段或者同步方法尽可能短,如果是非同步的数据结构,请使用Java collections 框架,而不要用更加昂贵的选择 如java.util.HashTable.

使用DataHandlers for SOAP Attachment

使用一个javax.activation.DataHandler for 一个 SOAP attachment 会提高性能。本段暂时没有接触过,略过,等用到了再翻译。

JAX-RPC specifies:
■ A mapping of certain MIME types to Java types.
■ Any MIME type is mappable to a javax.activation.DataHandler .
As a result, send an attachment (.gif or XML document) as a SOAP attachment to an RPC style
web service by utilizing the Java type mappings. When passing in any of the mandated Java type
mappings (appropriate for the attachment’s MIME type) as an argument for the web service, the
JAX-RPC runtime handles these as SOAP attachments.
For example, to send out an image/gif attachment, use java.awt.Image, or create a
DataHandler wrapper over your image. The advantages of using the wrapper are:
■ Reduced coding: You can reuse generic attachment code to handle the attachments because
theDataHandler determines the content type of the contained data automatically. This
feature is especially useful when using a document style service. Since the content is known
at runtime, there is no need to make calls to attachment.setContent(stringContent,
“image/gif”), for example.
■ Improved Performance: Informal tests have shown that usingDataHandler wrappers
doubles throughput for image/gif MIME types, and multiplies throughput by
approximately 1.5 for text/xml or java.awt.Image for image/* types.

【上篇】
【下篇】

抱歉!评论已关闭.