## NSNumber+XYCoordinates

So I occasionally have the problem where I want to store a bunch of x,y coordinates. I have solved this a number of ways in the past, but most recently had the idea of writing a category on NSNumber that simply stores two 16 bit integers, bitshifted together. So without further ado, here’s the github project for NSNumber+XYCoordinates.

My first version of this I couldn’t get negative numbers to work, but after some patient binary math explaining today at the coffee shop from my friend Matt, I finally got it to support numbers between -32767 and 32767.

Essentially, my category just adds the following methods:

NSNumber *xyNum = [NSNumber numberWithX:10 andY:10];

int x = [xyNum xValue];

int y = [xyNum yValue];

This seems to work pretty great, and is way less annoying than my previous favorite technique, which was to convert between NSString and CGPoint all the time.

So I got to thinking tonight… this should be fast, right? But I have no idea how fast, really, or how to compare it. So I wrote some test cases. Each of them assigns and then reads back out again some number of sequential integers using various techniques that I’ve used in the past. I compiled the following lists for different numbers of values:

100 Values

CGPointToNSString – size of 100 string objects in multidimensional array is 2263 (0.002 seconds).

NSDictionary – size of 100 objects in NSDictionary is 2413 (0.001 seconds).

NSSet – size of 100 objects in set is 1545 (0.004 seconds).

NSNumber+XYCoordinates – size of 100 objects in multi-dimensional array is 2033 (0.001 seconds).

10,000 Values

CGPointToNSString – size of 10000 string objects in multidimensional array is 241803 (0.162 seconds).

NSDictionary – size of 10000 objects in NSDictionary is 289593 (0.076 seconds).

NSSet – size of 10000 objects in set is 199798 (0.044 seconds).

NSNumber+XYCoordinates – size of 10000 objects in multi-dimensional array is 203503 (0.046 seconds).

1,000,000 Values

CGPointToNSString – size of 1000000 string objects in multidimensional array is 31702088 (10.187 seconds).

NSDictionary – size of 1000000 objects in NSDictionary is 38735561 (121.886 seconds).

NSSet – size of 1000000 objects in set is 25866828 (118.003 seconds).

NSNumber+XYCoordinates – size of 1000000 objects in multi-dimensional array is 25919832 (114.918 seconds).

You see that the technique compares favorably against CGPointToNSString, at 100 and 10,000 values, but somehow, the CGPointToNSString technique just blows it out of the water in terms of speed when we get to a million objects. (Still much smaller though.) I don’t fully understand this, but I guess maybe the C API is faster at high volumes? Let me know if you think you might have some insight!