Swift Array removeAll() performance (slow)

Using Swift Array I found removeAll() to be very slow and not perform well.

Especially the larger the array (the more objects it contains), the slower it was.

Is there a way to achieve good performance while performing the same function as removeAll() of an array?

"= []" This method also performed the same. And the way to declare the array after making it optional had the same performance.

swift / xcode is the latest version and is being tested on iOS 15.4 / iOS 14.8 / iphone6s.

Or can't Apple make a new function that speeds up the performance of removeAll()??

Replies

Using Swift Array I found removeAll() to be very slow and not perform well.

What do you measured exactly ? What does not perform well ?

If you look at doc you see
Complexity: O(n), where n is the length of the collection.

Which means it ***** linearly with n.

So effectively, = [] is much faster.

But removeAll can take a closure with where parameter, which makes it extremely useful.

  • We've been working on putting 20000 ViewControllers into an Array.

    We've seen that putting 20000 into an Array using append() doesn't take much time.

    However, it took a long time when I called removeAll() to delete the previously inserted 20000.

    It took about 15-20 seconds between calling removeAll and completing all append .

    We've even seen that using [] instead of removeAll() is time consuming which doesn't make much difference.

Add a Comment

20000 ViewControllers into an Array

Is it a real case or just for test ?

I assume that when removing, the VC needs to be deallocated. That's probably what takes time.