6、避免创建不必要的对象 (Effect java 学习笔记 )

150 阅读3分钟

  虽然构建和销毁一个对象的开销不大,但是也架不住量大呀。

  在每次需要时重用一个对象而不是创建一个新的对象通常是恰当的。重用可以更快更流行。如果对象是不可变的,它总是可以重用。(这是官方的)

新三年,旧三年,缝缝补补又三年,节约为本,虽然java有GC,家里有矿,我们也不能随便挥霍是吧

下面总结几个方法:

1、 通过使用静态工厂方法(不清楚可以去看考虑使用静态工厂方法替代构造方法

2、 当一些对象的创建相对来说比较昂贵的时候(耗内存,耗时间),建议缓存起来重复使用。比如Pattern 实例,这个可以缓存一下下。

3、 当一个对象是不可变的。例如,Map 接口的 keySet 方法返回 Map 对象的 Set 视图,包含 Map 中的所有 key。 天真地说,似乎每次调用 keySet 都必须创建一个新的 Set 实例,但是对给定 Map 对象的 keySet 的每次调用都返回相同的 Set 实例。 尽 管返回的 Set 实例通常是可变的,但是所有返回的对象在功能上都是相同的:当其中一个返回的对象发生变化时,所 有其他对象也都变化,因为它们全部由相同的 Map 实例支持。 虽然创建 keySet 视图对象的多个实例基本上是无 害的,但这是没有必要的,也没有任何好处。

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
        
    /**
     * Returns a {@link Set} view of the mappings contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation, or through the
     * <tt>setValue</tt> operation on a map entry returned by the
     * iterator) the results of the iteration are undefined.  The set
     * supports element removal, which removes the corresponding
     * mapping from the map, via the <tt>Iterator.remove</tt>,
     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
     * <tt>clear</tt> operations.  It does not support the
     * <tt>add</tt> or <tt>addAll</tt> operations.
     *
     * @return a set view of the mappings contained in this map
     */
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }
        
        
    }

4、自动装箱,实例如下

private static long sum() { 
    Long sum = 0L;
    for (long i = 0; i <= Integer.MAX_VALUE; i++) 
        sum += i; 
    return sum; 
}

  可以自测一下分别是Long和long的运行时间。优先使用基本类型而不是装箱的基本类型,也要注意无意识的自动装箱。

  需要说明一下的是,这里并不是暗示对象创建是昂贵的,应该避免创建对象。相反,使用构造方法创建和回收小的对 象是非常廉价,构造方法只会做很少的显示工作,尤其是在现代 JVM 实现上。 创建额外的对象以增强程序的清晰 度,简单性或功能性通常是件好事。

ps:如果有微信读书的书友,可以来微信读书群传送门找组织。