1. 程式人生 > >meepo--knowledge management

meepo--knowledge management

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能夠避免使用虛擬函式表從而更加經濟。 you can define final class when you need to create a class to connect to a data base or to a XML