On 29/05/2009, at 9:57 AM, John Ku wrote:

I have this original class with the following method:
- (void) update {
NSString *title = [[NSString alloc] init];
title = @"TEST";

This is incorrect for a start. You are leaking an empty string. You allocate and initialise it, then reassign its pointer to a new string, the constant @"TEST". The first one leaks.

This code suggests you aren't really grokking the difference between a string object you allocate and a constant string. You just need:

NSString* title = @"TEST";


NSPoint drawAtOrigin;
drawAtOrigin.x = 0;
drawAtOrigin.y = 10;

[title drawAtPoint: drawAtOrigin withAttributes: nil];
}


Here, I updated it trying to be efficient:

*.h header file has:*
NSString *title;
NSPoint drawAtOrigin;

*.m file has:*
- (id) init {
drawAtOrigin.x = 0;
drawAtOrigin.y = 10;
}

-(void) update {
[title drawAtPoint: drawAtOrigin withAttributes: nil];
}


Is this a more efficient way to code? Which coding practice is better in
terms of efficiency, memory, performance?

Who can say? Only a profiler.

However, wringing your hands over this sort of minutiae is pointless. In practice, there is not going to be any significant difference. In the latter case, you've used a little more memory for your object's ivars on the heap versus the same amount of memory temporarily on the stack. Typical coding practice is just to go with your first approach, most likely using the convenience function NSMakePoint().


The update method will get called often. So Im thinking there is no need to
create 'NSPoint drawAtOrigin' everytime.
Your thoughts?

Rasterizing text is a complex and difficult process, which is extremely hidden by the high-level drawAtPoint: method. The time it takes is aeons in comparison to assigning the NSPoint structure. Don't sweat it, it will make no difference whatsoever. Assigning on an as- needed basis is a more typical pattern, doesn't clutter your object with extraneous ivars and is likely to be a teeny-weeny bit faster though probably immeasurably so.

General point here: don't optimise at this stage. Write the simplest, clearest, most readable, most correct code you can, get it working, then if you appear to run into performance problems later, profile it, find out where the bottlenecks really are, work on those.

If you are drawing many text elements a lot, setting up and reusing a NSLayoutManager can be fruitful, along with other text-caching techniques may yield some improvements in performance. "Optimising" the setting of the NSPoint will not.

--Graham







_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to