Steve
Steve

Reputation: 6362

Is there a cost to using NSLog liberally?

As a newer programmer, I've discovered the magic of NSlog, and use it all through my code. It's been extremely helpful (along with NSZombieEnabled) in debugging.

I can see a definite performance hit on the simulator as it prints out all this stuff. I don't think I see any such hit on devices, but I'm not sure.

So does it cost anything to leave all the NSLogs in? Is it using more memory on the device? Or does the compiler just ignore them, like it does comments when I compile for a device?

EDIT:

Here's what I implemented, per the suggestion from rano.

In my App_Prefix.pch file, I added:

// DLog is almost a drop-in replacement for NSLog
// DLog();
// DLog(@"here");
// DLog(@"value: %d", x);
// Unfortunately this doesn't work DLog(aStringVariable); you have to do this instead     DLog(@"%@", aStringVariable);
#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif

// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

And then in my Project Info inspector, for the Debug configuration, under the heading GCC 4.2 - Preprocessing, I added the value DEBUG to the top entry called, Preprocessor Macros.

Works like a charm - DLog outputs when I build a Debug version and ALog always outputs.

Upvotes: 6

Views: 1338

Answers (3)

dbainbridge
dbainbridge

Reputation: 1202

The answers above are outdated. You should simply use CocoaLumberjack is vastly superior to NSLog and provides much more functionality then the above answers.

Upvotes: 0

Steven Fisher
Steven Fisher

Reputation: 44866

NSLog is not implemented as a macro, so there will definitely be a cost. Quantifying it and deciding if it is important is harder. The only sure way to do that is to measure your own application.

Upvotes: 0

rano
rano

Reputation: 5666

NSLog surely is more pricy than a simple printf but is a little more integrated into the objective-C and Cocoa framework.

By the way when you are seriously programming you will notice that it is unsufficient to most of your needs. Take a look at this article and its references to have an idea on how to replace it in a smart way.

In that way you can also have the compiler to ignore it when it is no more useful (e.g. when you will release your piece of code). In general you could #ifdef the calling to a log function in computing intensive loops/sequences of code.

Upvotes: 6

Related Questions