Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4553660
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T16:58:41+00:00 2026-05-21T16:58:41+00:00

Suppose I have a NSDictionary with two sub collections of a NSArray and a

  • 0

Suppose I have a NSDictionary with two sub collections of a NSArray and a NSDictionary:

NSMutableDictionary *mkDict(void){
    NSMutableDictionary *dict=[NSMutableDictionary dictionary];
    NSMutableDictionary *sub=[NSMutableDictionary dictionary];
    NSMutableArray *array= [NSMutableArray array];
    [dict setObject:array forKey:@"array_key"];
    [dict setObject:sub forKey:@"dict_key"];
    return dict;
}

There are a multitude of ways to access a single element of the sub-collection, and I choose to time three of them.

The first way is to indirectly access the subelements by accessing the key of the parent:

void KVC1(NSMutableDictionary *dict, int count){

    for(int i=0; i<count; i++){
        char buf1[40], buf2[sizeof buf1];
        snprintf(buf1,sizeof(buf1),"element %i", i);
        snprintf(buf2, sizeof buf2, "key %i", i);

        [[dict objectForKey:@"array_key"] 
          addObject:
             [NSString stringWithUTF8String:buf1]];
        [[dict objectForKey:@"dict_key"] 
          setObject:[NSString stringWithUTF8String:buf1] 
          forKey:[NSString stringWithUTF8String:buf2]];
    }
}

The second is to use KeyPath access:

void KVC2(NSMutableDictionary *dict, int count){

    for(int i=0; i<count; i++){
        char buf1[40], buf2[sizeof buf1], buf3[sizeof buf1];
        snprintf(buf1,sizeof(buf1),"element %i", i);
        snprintf(buf2, sizeof buf2, "key %i", i);
        snprintf(buf3, sizeof buf3, "dict_key.key %i",i);

        [dict insertValue:
             [NSString stringWithUTF8String:buf1] 
            atIndex:i inPropertyWithKey:@"array_key"];
        [dict setValue:
             [NSString stringWithUTF8String:buf1] 
            forKeyPath:
             [NSString stringWithUTF8String:buf3]];
    }
}

And the third, similar to the first, is to access a pointer to the sub element, then use that pointer:

void KVC3(NSMutableDictionary *dict, int count){

    NSMutableArray *subArray = [dict objectForKey:@"array_key"];
    NSMutableDictionary *subDict = [dict objectForKey:@"dict_key"];

    for(int i=0; i<count; i++){
        char buf1[40], buf2[sizeof buf1];
        snprintf(buf1,sizeof(buf1),"element %i", i);
        snprintf(buf2, sizeof buf2, "key %i", i);

        [subArray addObject:[NSString stringWithUTF8String:buf1]];
        [subDict 
           setObject:
            [NSString stringWithUTF8String:buf1] 
           forKey:
            [NSString stringWithUTF8String:buf2]];
    }
}

Here is the timing code:

#import <Foundation/Foundation.h>
#import <mach/mach_time.h>

// KVC1, KVC2 and KVC3 from above...

#define TIME_THIS(func,times) \
({\
mach_timebase_info_data_t info; \
mach_timebase_info(&info); \
uint64_t start = mach_absolute_time(); \
for(int i=0; i<(int)times; i++) \
func ; \
uint64_t duration = mach_absolute_time() - start; \
duration *= info.numer; \
duration /= info.denom; \
duration /= 1000000; \
NSLog(@"%i executions of line %i took %lld milliseconds", times, __LINE__, duration); \
});

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSMutableDictionary *dict=mkDict();
    NSMutableDictionary *dict2=mkDict();
    NSMutableDictionary *dict3=mkDict();

    TIME_THIS(KVC1(dict,1000),10);
    TIME_THIS(KVC2(dict2,1000),10);
    TIME_THIS(KVC3(dict3,1000),10);

    if([dict isEqualToDictionary:dict2])
        NSLog(@"And they are the same...");
    [pool drain];
    return 0;
}

Here are the results:

10 executions of line 256 took 57 milliseconds
10 executions of line 257 took 7930 milliseconds
10 executions of line 258 took 46 milliseconds
And they are the same...

Question: Why is the OS X Snow Leopard / Lion suggested method of using KeyPaths so stinking slow? If you increase the size of count to 10,000 or more, KVC2 becomes infinitely slow where the other two methods increase linearly.

Am I doing something wrong? Is there a better idiom to access a single element of a sub collection in a dictionary?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T16:58:42+00:00Added an answer on May 21, 2026 at 4:58 pm

    In KVC2(), you send

    [dict insertValue:[NSString stringWithUTF8String:buf1] 
              atIndex:i
    inPropertyWithKey:@"array_key"]; 
    

    The documentation for that method states the following:

    The method insertIn<Key>:atIndex: is invoked if it exists. If no corresponding scripting-KVC-compliant method (insertIn<Key>:atIndex:) is found, this method invokes mutableArrayValueForKey: and mutates the result.

    Since the message is being sent to dict, an instance of NSDictionary, there is no -insertIn<Key>:atIndex: method, hence -mutableArrayValueForKey: is sent. The documentation for this method states the following:

    Return Value
    A mutable array proxy that provides read-write access to the ordered to-many relationship specified by key.

    Discussion
    Objects added to the mutable array become related to the receiver, and objects removed from the mutable array become unrelated. The default implementation recognizes the same simple accessor methods and array accessor methods as valueForKey:, and follows the same direct instance variable access policies, but always returns a mutable collection proxy object instead of the immutable collection that valueForKey: would return.

    So what’s happening is that at each iteration:

    1. A proxy mutable array is created as a mutable copy of the original array;
    2. An object is added to the proxy array;
    3. The proxy array adds the same object to the original array.

    If you use Instruments to profile your program, you’ll notice that about 50% of the processing time is spent on -[NSKeyValueSlowMutableArray insertObject:atIndex:] — I think it’s safe to assume that NSKeyValueSlowMutableArray is the proxy array and its name should be a clue of its performance.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose I have a macro defined as this: #define FOO(x,y) \ do { int
Suppose I have this code: class Num: def __init__(self,num): self.n = num def getn(self):
Suppose you have the following object hierarchy: class Vehicle { public: virtual ~Vehicle() {}
Suppose i have an XML file, that i use as local database, like this):
Suppose I have a stream of [acme] objects that I want to expose via
Suppose we have buyers and sellers that are trying to find each other in
suppose i have label and button on textbox and i want that if i
I have 2 subviews on the stage (a splash screen, and the main screen)
I am struggling with geolocation on simulator, but recently, I have tested it directly
So my first app I am making is for jailbroken devices. I must say

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.