tailieunhanh - Effective Java Programming Language Guide phần 2

Các phương pháp isBabyBoomer một cách không cần thiết tạo ra một Lịch mới, múi giờ, và hai trường hợp ngày mỗi lần nó được gọi. Các phiên bản sau đó tránh được điều này không hiệu quả với một initializer tĩnh: Phiên bản cải tiến của lớp người tạo ra các trường hợp Lịch, múi giờ, và ngày chỉ một lần, khi nó được khởi tạo, thay vì tạo ra chúng | Effective Java Programming Language Guide The isBabyBoomer method unnecessarily creates a new Calendar TimeZone and two Date instances each time it is invoked. The version that follows avoids this inefficiency with a static initializer class Person private final Date birthDate public Person Date birthDate birthDate The starting and ending dates of the baby boom. private static final Date BOOM_START private static final Date BOOM_END static Calendar gmtCal GMT 1946 1 0 0 0 BOOM_START 1965 1 0 0 0 BOOM_END public boolean isBabyBoomer return BOOM_START 0 BOOM_END 0 The improved version of the Person class creates Calendar TimeZone and Date instances only once when it is initialized instead of creating them every time isBabyBoomer is invoked. This results in significant performance gains if the method is invoked frequently. On my machine the original version takes 36 000 ms for one million invocations while the improved version takes 370 ms which is one hundred times faster. Not only is performance improved but so is clarity. Changing boomStart and boomEnd from local variables to final static fields makes it clear that these dates are treated as constants making the code more understandable. In the interest of full disclosure the savings from this sort of optimization will not always be this dramatic as Calendar instances are particularly expensive to create. If the isBabyBoomer method is never invoked the improved version of the Person class will initialize the BOOM_START and BOOM_END fields unnecessarily. It would be possible to eliminate the unnecessary initializations by lazily initializing these fields Item 48 the first time the isBabyBoomer method is invoked but it is not recommended. As is often the case with lazy initialization it would complicate the implementation and would be .

TỪ KHÓA LIÊN QUAN
crossorigin="anonymous">
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.