To debug our Android code we have put System.out.println(string) which will let us know how many times a function has been called. The other method would have been to put a flag and keep on incrementing it after every function call. And then at the end printing the final value of flag by System.out.println(...). (practically in my application the function will be called thousands of time)
My question is: In terms of CPU Resources and Clock Cycles which one is lighter: increment operation Or System.out.println?
Incrementing is going to be much, much more efficient – especially if you’ve actually got anywhere for that output to go. Think of all the operations required by
System.out.printlnvs incrementing a variable. Of course, whether the impact will actually be significant is a different matter – and if your method is already doing a lot of work, then aSystem.out.printlncall may not actually make much difference. But if you just want to know how many times it was called, then keeping a counter makes more sense than looking through the logs anyway, IMO.I would recommend using
AtomicLongorAtomicIntegerinstead of just having a primitive variable, as that way you get simple thread-safety.