Skip to content

Commit 0bb0c2c

Browse files
committed
NSCache is very slow. Use an per-instance NSMutableDictionary instead
1 parent a86b467 commit 0bb0c2c

File tree

2 files changed

+7
-15
lines changed

2 files changed

+7
-15
lines changed

Classes/SBJsonStreamWriter.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,9 @@
8282
8383
*/
8484

85-
@interface SBJsonStreamWriter : NSObject
85+
@interface SBJsonStreamWriter : NSObject {
86+
NSMutableDictionary *cache;
87+
}
8688

8789
@property (nonatomic, assign) SBJsonStreamWriterState *state; // Internal
8890
@property (nonatomic, readonly, retain) NSMutableArray *stateStack; // Internal

Classes/SBJsonStreamWriter.m

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,6 @@
3939
static NSNumber *kPositiveInfinity;
4040
static NSNumber *kNegativeInfinity;
4141

42-
static id kStaticStringCache;
43-
4442

4543
@implementation SBJsonStreamWriter
4644

@@ -57,16 +55,6 @@ + (void)initialize {
5755
kNegativeInfinity = [NSNumber numberWithDouble:-INFINITY];
5856
kTrue = [NSNumber numberWithBool:YES];
5957
kFalse = [NSNumber numberWithBool:NO];
60-
61-
Class cacheClass = NSClassFromString(@"NSCache");
62-
if (cacheClass) {
63-
NSLog(@"%s NSCache supported", __FUNCTION__);
64-
kStaticStringCache = [[cacheClass alloc] init];
65-
}else {
66-
NSLog(@"%s NSCache not supported", __FUNCTION__);
67-
}
68-
69-
7058
}
7159

7260
#pragma mark Housekeeping
@@ -79,6 +67,7 @@ - (id)init {
7967
maxDepth = 32u;
8068
stateStack = [[NSMutableArray alloc] initWithCapacity:maxDepth];
8169
state = [SBJsonStreamWriterStateStart sharedInstance];
70+
cache = [[NSMutableDictionary alloc] initWithCapacity:32];
8271
}
8372
return self;
8473
}
@@ -87,6 +76,7 @@ - (void)dealloc {
8776
self.error = nil;
8877
self.state = nil;
8978
[stateStack release];
79+
[cache release];
9080
[super dealloc];
9181
}
9282

@@ -294,7 +284,7 @@ - (BOOL)writeString:(NSString*)string {
294284
[state appendSeparator:self];
295285
if (humanReadable) [state appendWhitespace:self];
296286

297-
NSMutableData *buf = [kStaticStringCache objectForKey:string];
287+
NSMutableData *buf = [cache objectForKey:string];
298288
if (!buf) {
299289

300290
NSUInteger len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
@@ -321,7 +311,7 @@ - (BOOL)writeString:(NSString*)string {
321311
[buf appendBytes:utf8 + written length:i - written];
322312

323313
[buf appendBytes:"\"" length:1];
324-
[kStaticStringCache setObject:buf forKey:string];
314+
[cache setObject:buf forKey:string];
325315
}
326316

327317
[delegate writer:self appendBytes:[buf bytes] length:[buf length]];

0 commit comments

Comments
 (0)