Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 268
L_Sonic Avatar asked May 02 '13 11:05

L_Sonic


2 Answers

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.

like image 87
Nishant Tyagi Avatar answered Nov 10 '22 19:11

Nishant Tyagi


First, your KVC expression won't work; KVC can't be used to retrieve struct members (save for very limited cases where a class has a special implementation of valueForKey: that does special processing).

Secondly, this smells like premature optimization.

Have you actually quantified a performance problem related to this code?

If not, you are wasting your time "optimizing" this code path.

That aside, using KVC for such operations adds considerable fragility to your code. The compiler cannot verify the expression passed to valueForKey: and, thus, what would be a compile time error or warning is now an error at runtime that'll only be found if you execute that codepath.

like image 6
bbum Avatar answered Nov 10 '22 18:11

bbum