I recently commented the MSDN article How to: Access Server Controls by ID regarding the suggested FindControlRecursive function.
Let’s assume that the contorl to find is the 10th contained in the rootControl: in the suggested code, before find it, the method will search it in each one of the previous 9 and in their hierarchy.
A very small change in that code make it better performing:
public static Control FindControlRecursive(Control _control, string _strId) { if (_control.ID == _strId) return _control; if (_control.FindControl(_strId) != null) return _control.FindControl(_strId); foreach (Control cntr in _control.Controls) { Control _resControl = FindControlRecursive(cntr, _strId); if (!(_resControl == null)) return _resControl; } return null; }
The suggested addition is obviously the line:
if (_control.FindControl(_strId) != null) return _control.FindControl(_strId);
it will search the control to find in the current container and in the above supposed case really faster than after searching it in the 9 previous controls hierarchy.
15/01/2013 UPDATE:
Someone tested this optimization and found that it’s slower than the original. That means that the FindControl method is quite slow.
I think in some cases (rarely) it could be faster with a little change:
Control _tmpControl = _control.FindControl(_strId);
if (_tmpControl != null) return _tmpControl.FindControl(_strId);