-1

When I was learning C, I was taught to do stuff, say, if I wanted to loop through a something strlen(string) times, I should save that value in an 'auxiliary' variable, say count and put that in the for condition clause instead of the strlen, as I'd save the need of processing that many times.

Now, when I started learning Java, I noticed this is quite not the norm. I've seen lots of code and programmers doing just what I was told not to do in C.

What's the reason for this? Are they trading efficiency for 'readibility'? Or does the compiler manage to fix that?

E: This is NOT a duplicate to the linked question. I'm not simply asking about string length, mine is a more general question.

YoTengoUnLCD
  • 600
  • 7
  • 15
  • Modern compilers are now intelligent enough to do it implicitly. – AhmadWabbi May 10 '16 at 00:54
  • It's mostly programmer preference. As a general rule, if you're need the result of your function call in multiple places, it's a good idea to set it to a preliminary variable. Depending on the compiler you're using, it will most likely be optimized for you. – blacktide May 10 '16 at 00:54
  • 1
    `Java != C` and `C != Java` just because the syntax is similar does not mean anything else is. –  May 10 '16 at 00:57
  • @Casey Is there any way to see if the compiler will actually change this? – YoTengoUnLCD May 10 '16 at 00:57
  • you have access to the byte code that gets generated, that tells you all yo need to know that can be known at compile time, everything else is done JIT, which is where most of the magic happens. –  May 10 '16 at 00:58
  • 1
    @YoTengoUnLCD Sure, compile your Java class and take a look at the bytecode it generates. – blacktide May 10 '16 at 00:58
  • then you are doing things blindly, good general advice for dog owners is not good general advice for cat owners or bird owners or alligator owners. And yes, this is an **exact** duplicate of the marked duplicate, in every way. –  May 10 '16 at 00:59

1 Answers1

-2

In the old times, every function call was expensive, compilers were dumb, usable profilers yet to come, and computers slow. This way C macros and other terrible things were born. Java is not that old.

Efficiency is important, but the impact of most program parts on efficiency is very small. But reading code still needs programmers time and this is much more costly than CPU. So we'd better optimize for readability most of the time and care about speed just in the most important places.

A local variable can make the code simpler, when it avoids repetitions of complicated expressions - this happens sometimes. It can make it faster, when it avoids expensive computation which the compiler can't do - this happens rather rarely. When neither condition is met, it's just a wasted line, so why bother?

maaartinus
  • 44,714
  • 32
  • 161
  • 320