Search code examples
iphoneiosobjective-cipadkvc

KVC vs fast enumeration


Which of the following is faster and why?

CGFloat sum = 0;
for (UIView *v in self.subviews)
    sum += v.frame.size.height;

or

CGFloat sum = [[self.subviews valueForKeyPath:@"@sum.frame.size.height"] floatValue];

Solution

  • Really, a lot of how elegant (or clever) a language is comes down to how well it avoids loops. for, while; even fast enumeration expressions are a drag. No matter how you sugar-coat them, loops will be a block of code that does something that is much simpler to describe in natural language.

    "get me the average salary of all of the employees in this array",

    double totalSalary = 0.0;
    for (Employee *employee in employees) {
      totalSalary += [employee.salary doubleValue];
    }
    double averageSalary = totalSalary / [employees count];
    

    versus...

    Fortunately, Key-Value Coding gives us a much more concise--almost Ruby-like--way to do this:

    [employees valueForKeyPath:@"@avg.salary"];
    

    KVC Collection Operators allows actions to be performed on a collection using key path notation in valueForKeyPath:.

    Any time you see @ in a key path, it denotes a particular aggregate function whose result can be returned or chained, just like any other key path.

    Fast Enumeration is Faster then KVC.

    Hope it helps you.