将class声明为final的好处

【转】http://121dog198.blog.163.com/blog/static/50859950201422612247819/


1. Virtual (overridden) methods generally are implemented via some sort of table (vtable) that is ultimately a function pointer. Each method call has the overhead of having to go through that pointer. When classes are marked final then all of the methods cannot be overridden and the use of a table is not needed anymore - this it is faster.

Some VMs (like HotSpot) may do things more intelligently and know when methods are/are not overridden and generate faster code as appropriate.

虚函数一般是通过函数表实现的,这个虚函数表其实是一个函数指针,每次函数调用都需要查询函数指针,如果一个类被标为final,那么所有的方法不会被重载,也就不需要这样的函数指针了,因而性能变得很好。 现在很多虚拟机都非常智能化,以至于能够判断方法是否被重载,从而产生更快的codes。

2.The best use of final that I've seen is in library code: Making a class and/or methods final, in a library class, prevents your customers from extending it, making their code overly dependent on your implementation. Doing this enables you to make changes to your library class with confidence that they won't break client code. I'm often angry when vendors do this to me, the customer, because it prevents mocking and other good things. But I see why they do it.

可以阻止你的客户集成你实现的类,当你修改自己的库时,不用担心打牌客户的codes。

3.

3.1. Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables. 

jvm能够缓存final变量,应用程序也能够缓存频繁使用的final变量
3.2. Final variables are safe to share in multi-threading environment without additional synchronization overhead. 
final变量能够在多线程环境下安全使用
3.3. Final keyword allows JVM to optimized method, variable or class.
final变量容许JVM优化方法、变量和类
4. As you see there are a lot of JIT compilers in the world and mainly you don't know which one will be used to execute (and optimize) your Java program on the fly, so you should keep in mind that methods of final classes can be used by JIT more optimally because it can address them directly since their methods can't be overridden by successors and JIT can make some economy to avoid virtual tables usage. I repeat that it depends on used JIT.
世界上有很多种JIT编译器,你不知道你的java程序到底使用哪种编译器编译,但是你如果将编译器设计为final的,jit能够避免使用虚函数表从而更加经济。
参考资料:
http://www.linkedin.com/groups/What-are-advantages-making-class-70526.S.59879045
http://stackoverflow.com/questions/3961881/why-defining-class-as-final-improves-jvm-performance

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值