Hari Ganesan
Hari Ganesan

Reputation: 530

speed of UIView add/remove subview versus hiding/showing

Let's say I have a full-screen UIView that overlays the main screen when a button is touched, and then goes away when this overlayed view is touched. This UIView could either be added and removed from the current view using addSubview: and removeFromSuperview, or it could be added when the current view is initialized and then shown and hidden by accessing and setting the hidden property of the UIView. Which is generally faster and better for performance (or are they the same)?

Upvotes: 7

Views: 2243

Answers (3)

Duncan C
Duncan C

Reputation: 131501

As Clay says, showing hiding will probably be faster, but you would need sensitive instruments to detect the difference. It's going to be single-digit hundredths of a second at the most, and probably much less than that. You won't be able to sense the difference "by eye".

Thus what matters is other things, like what is the easiest to understand and maintain? One problem with making a view exist in the view controller and showing/hiding it at well is that the layout of the view covers the other contents of the view controller and makes it hard to manage.

You can create a second XIB (or an XIB that goes along with your storyboard) that has your view controller's class as it's "File's owner" and link up IBOutlets to the views you want. Then you load the view from an XIB when you need it, install it as a subview of your current view. Then you remove it from the superview when you're done with it. I use that approach a fair amount.

Upvotes: 0

larva
larva

Reputation: 5148

I did try add imageView and try loop 1000000 times to hide and show in each loop and add remove in each loop. Result is hide and show take 1s to do 1000000 loop. And add remove take 3s. I do it in simulator :)

Upvotes: 3

Clay Bridges
Clay Bridges

Reputation: 11890

I'd bet show and hide will be faster. The other way requires object creation/destruction, and fiddling with subviews.

More importantly, I think show and hide will be simpler, and the fight against complexity is paramount.

Upvotes: 2

Related Questions