Fast removeLast array is extremely slow

The call to removeLast very slow (it takes a few minutes to pull out 77k elements). the documentation says O (1) and I think the implementation will simply reduce the size of the array. Obviously not:

stack trace indicating <code> removeLast </code> memmove call

Why does it call remove(at: Int) ?

This playback example is slower than I expected (I'm used to C ++ std::vector performance), but still not as slow as what I see in my code:

 var array = [ Int ]() for i in 0..<262144 { array.append(i) } print ("done appending") // we get here immediately let n = array.count for _ in 0..<n { array.removeLast() // popLast is also slow } print ("done") 

It takes 16 seconds on my car. An equivalent C ++ program takes 0.002 seconds.

+5
source share
1 answer

The problem is how you test. No speed test in a Debug assembly makes sense in any way. That's why you should always have a profile in the Tools. It uses the Release assembly. For realistic results, profile in Tools on your device. Everything else is an illusion.

So make the Release build, not the Debug build. You will see that you actually get print statements instantly.

Results (on my computer, not on the device, because I was too lazy to pull the phone out of my pocket), displaying seconds from the reference date:

 starting 506917910.056674 done appending 506917910.060245 done 506917910.069827 
+4
source

Source: https://habr.com/ru/post/1263223/


All Articles