Sunday, May 17, 2015

How Not to Crash #2: Mutation Exceptions

Brent Simmons:

You get a collection from somewhere and enumerate it — and then you get an error about the collection being mutated as it was being enumerated. The app crashes.

[…]

You might push back, citing performance or memory use issues or both — but I’ll admit something: I’m a performance junkie, and I spend an inappropriate amount of time in Instruments making sure things are fast and use a non-weird amount of memory. And I’ve never, ever found this to be a problem. If your app has performance or memory use issues, the problem is something else, not these copies.

[…]

There’s a general point: if you’re getting a collection from code that isn’t yours, it doesn’t hurt to be defensive and enumerate a copy.

Swift does something similar automatically, although it probably doesn’t work when enumerating an NSArray that you receive.

Comments RSS · Twitter

Leave a Comment