美文网首页
Item 6: Avoid creating unnecessa

Item 6: Avoid creating unnecessa

作者: 空谷幽心 | 来源:发表于2018-08-02 09:23 被阅读8次

    笔记

    • An object can always be reused if it is immutable。

    • You can often avoid creating unnecessary objects by using static factory methods (Item 1) in preference to constructors on immutable classes that provide both.

    • While String.matches is the easiest way to check if a string matches a regular expression, it’s not suitable for repeated use in performance-critical situations.

    • It would be possible to eliminate the initialization by lazily initializing the field (Item 83) the first time the isRomanNumeral method is invoked, but this is not recommended. As is often the case with lazy initialization, it would complicate the implementation with no measurable performance improvement (Item 67)

    • consider the case of adapters [Gamma95], also known as views. An adapter is an object that delegates to a backing object, providing an alternative interface. Because an adapter has no state beyond that of its backing object, there’s no need to create more than one instance of a given adapter to a given object.

    • prefer primitives to boxed primitives, and watch out for unintentional autoboxing.

    • Creating additional objects to enhance the clarity, simplicity, or power of a program is generally a good thing.

    • Conversely, avoiding object creation by maintaining your own object pool is a bad idea unless the objects in the pool are extremely heavyweight.

    • Generally speaking, however, maintaining your own object pools clutters your code, increases memory footprint, and harms performance.

    理解与思考

    1. 必要的情况下,弄清楚调用的每个方法,创建的每个对象背后发生的事情。如果创建了重量级的对象,就可以考虑缓存对象。
    2. 平时以提升可读性,可维护性,减少复杂性为目标,不能把事情弄得太复杂。如果因此带来了问题,就需要权衡取舍,做一些改进。

    实践

    1. 自动装箱的例子,原始long类型竟然比装箱的Long快10倍,有点不可思议。

    相关文章

      网友评论

          本文标题:Item 6: Avoid creating unnecessa

          本文链接:https://www.haomeiwen.com/subject/bforvftx.html