Mutable vs immutable objects

前端 未结 12 1570
囚心锁ツ
囚心锁ツ 2020-11-22 09:17

I\'m trying to get my head around mutable vs immutable objects. Using mutable objects gets a lot of bad press (e.g. returning an array of strings from a method) but I\'m hav

12条回答
  •  死守一世寂寞
    2020-11-22 09:52

    Mutable collections are in general faster than their immutable counterparts when used for in-place operations.

    However, mutability comes at a cost: you need to be much more careful sharing them between different parts of your program.

    It is easy to create bugs where a shared mutable collection is updated unexpectedly, forcing you to hunt down which line in a large codebase is performing the unwanted update.

    A common approach is to use mutable collections locally within a function or private to a class where there is a performance bottleneck, but to use immutable collections elsewhere where speed is less of a concern.

    That gives you the high performance of mutable collections where it matters most, while not sacrificing the safety that immutable collections give you throughout the bulk of your application logic.

提交回复
热议问题