• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Performance!!

 
Ranch Hand
Posts: 305
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Everybody,

I am bit confused and try to find out which is the best way of Initializing the variable sum here. My questions are:

1. If I define the second way, does it mean it will put more load on the system.

2. does the efficiency get reduce in second method, as it is Initializing every time.

Please help me to find a answer.

Thanks & regards

Arun

Code I:

Code II:

[ March 27, 2006: Message edited by: arun mahajan ]
 
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't know about the efficiency, although I suspect it is negligible in a simple example. The recursive version executes far slower, so it might affect that in a negative way.

The second is just plain bad programming, regardless of efficiency. Why re-declare the same variable that is used over and over? It is pointless and illogical, don't do it.
[ March 27, 2006: Message edited by: Rusty Shackleford ]
 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is always a good practise to re-use as many variables as possible in a program, as initializing new variables always ends up making more and more use of the heap..which is not a good practise if you don't need the new variables.

So in the second case, you are definitely wasting heap memory, and if "sum" were to be an object, you;d end up creating a large number of redundant objects.

Although you will not be putting too much extra load in terms of execution time on your PC, but as I said, if sum were an object, you could end up slowing your program down, due to too many objects.
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

It is always a good practise to re-use as many variables as possible in a program


Absolutely not. If you had said something like "If utmost runtime performance is the only concern, and readability and maintainability of the code does not matter at all, then re-use of variables is a good thing", then one could argue about it. But not always, and it's certainly not good practice.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[Rusty]: The recursive version executes far slower, so it might affect that in a negative way.

What recursive version? I don't see any recursion in either code sample.

If you think one of those bits of code executes slower than the other, I suggest testing it. I believe you will find they both perform the same. Even "if utmost runtime performance is the only concern" - there is no performance penalty for declaring a local variable inside a loop. It performs the same as if you had declared it outside.

There is a tiny chance that someone may one day make a compiler which behaves differently, but every time this subject has come up in the past and someone studied the byte codes, we confirmed that the compiler generates the same byte codes (or effectively the same byte codes) in each case. I would say it's very unlikely that will change anytime soon. But feel free to test this yourself to confirm.

[Rusty]: The second is just plain bad programming, regardless of efficiency. Why re-declare the same variable that is used over and over? It is pointless and illogical, don't do it.

[Ashish]: It is always a good practise to re-use as many variables as possible in a program, as initializing new variables always ends up making more and more use of the heap..


I strongly disagree with both of these statements. These are local variables, therefore on the stack rather than the heap. If you study the bytecode generated you will find that there's no reallocation occurring - the compiler just keeps reusing the same memory space each time through the loop. So it costs you nothing to redeclare the variable. More important are two other effects: (1) by eclaring a variable as clase as possible to where it's actually used, you make it easier to understand that code. And (2) by restricting the scope of the variable to the minimum required (declare the variable as late as possible, inside blocks if possible), you typically would decrease the chance of errors which might occur from accidentally re-using a variable name somewhere else. Many of us have loop variables named i, or Iterators named it or iter - if you have two loops one after another, and in the second loop you type i when you should have said i2 (or "iter" when you should have typed "iter2", you get a bug. Such bugs are easily avoided (or promptly detected) if each loop variable is only defined within the loop it's needed for.

I suggest reading Effective Java, Item 29: Minimize the scope of local variables. Also the rest of the book is strongly recommended, for other reasons.
 
author
Posts: 288
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I also, strongly recommend effective java. It is a great book for someone with 2+ years of experience.


Both your programs are pretty straight forward and should not make any difference in terms of performance.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ashish Chopra:
So in the second case, you are definitely wasting heap memory, and if "sum" were to be an object, you;d end up creating a large number of redundant objects.



Variables never are objects. They are either primitives or references. The number of objects created on the heap has nothing to do at all with how many local variables you declare.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jim Yingst:
by declaring a variable as clase as possible to where it's actually used, you make it easier to understand that code.



Additionally, by reducing the scope of a variable as much as possible, the compiler actually can decide to reuse the memory space for another variable later on.
 
Rusty Shackleford
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jim Yingst:
[Rusty]: The recursive version executes far slower, so it might affect that in a negative way.

What recursive version? I don't see any recursion in either code sample.

If you think one of those bits of code executes slower than the other, I suggest testing it. I believe you will find they both perform the same. Even "if utmost runtime performance is the only concern" - there is no performance penalty for declaring a local variable inside a loop. It performs the same as if you had declared it outside.

There is a tiny chance that someone may one day make a compiler which behaves differently, but every time this subject has come up in the past and someone studied the byte codes, we confirmed that the compiler generates the same byte codes (or effectively the same byte codes) in each case. I would say it's very unlikely that will change anytime soon. But feel free to test this yourself to confirm.



I never said that he had a recursive version. Perhaps I should have said 'A'instead of 'The' to avoid simple misunderstandings.

I also did not say if it was a performance penalty, but I did say it was pointless. I would like to see arguments why someone should write it like the second part.


[b][Rusty]: The second is just plain bad programming, regardless of efficiency. Why re-declare the same variable that is used over and over? It is pointless and illogical, don't do it.



I strongly disagree with both of these statements. These are local variables, therefore on the stack rather than the heap. If you study the bytecode generated you will find that there's no reallocation occurring - the compiler just keeps reusing the same memory space each time through the loop. So it costs you nothing to redeclare the variable. More important are two other effects: (1) by eclaring a variable as clase as possible to where it's actually used, you make it easier to understand that code. And (2) by restricting the scope of the variable to the minimum required (declare the variable as late as possible, inside blocks if possible), you typically would decrease the chance of errors which might occur from accidentally re-using a variable name somewhere else. Many of us have loop variables named i, or Iterators named it or iter - if you have two loops one after another, and in the second loop you type i when you should have said i2 (or "iter" when you should have typed "iter2", you get a bug. Such bugs are easily avoided (or promptly detected) if each loop variable is only defined within the loop it's needed for.

I suggest reading Effective Java, Item 29: Minimize the scope of local variables. Also the rest of the book is strongly recommended, for other reasons.



So you think it is ok? You do realize that just because something does not adversely effect a program, doesn't mean it should be done. The second code example is bad programming practice, period.
[ March 28, 2006: Message edited by: Rusty Shackleford ]
 
Marshal
Posts: 28177
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Rusty Shackleford:
The second code example is bad programming practice, period.

You said that before, but you didn't say why. So how about saying why this time?
 
Rusty Shackleford
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because doing something that is not necessary is never something you should do. Regardless of whether it is legal or has no adverse effects on a program.

Flip it around, what does redeclaring a variable inside a loop buy you? If the answer is nothing(and it is), then there is no reason to do it. Do that in an academic assignment or real world code at your job and see what it buys you.
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Declaring a variable close to where it's used helps readability, prevents scope errors, and most important to me helps the refactor tool in Eclipse. If the loop grows big enough to be in a separate method or class, you or the tool can cut/paste variables declared inside the loop with no effort.

It took me a long time to get to this style. I started in COBOL where all fields are declared at the top of the program, then a 370 Assembler class where they taught declare all the data at the end of the program and then Pascal where the style I took up was to very neatly declare variables at the top of each function.

BTW: COBOL folks are the champs at reusing variables in memory, files and databases. And it's absolutely disastrous. Never fall to the temptation.
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hmmm, I suppose I should've moved this to the Performance forum in the first place. Because even though this has little or no bearing in performance, we're certainly talking about performance a lot. And Beginner doesn't seem a good fit. So, off we go...
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[Rusty]: So you think it is ok? You do realize that just because something does not adversely effect a program, doesn't mean it should be done.

I do realize this, which is why if you had read the rest of my post, you would've seen that I went on to give positive reasons to do it. As did Ilja. Declaring a variable inside a loop has no effect at all on performance (with an exception noted by Ilja, discussed below), but it has positive benefits for readability and catching certain errors. But there's not much I can do for you if you won't read what was already written.

----

Ilja noted that reducing scope makes it easier for the compiler to reuse the memory later. Reuse for other, unrelated variables I assume - the space is already automatically reused for a "redeclared" variable in a loop; that was the point of my first paragraph earlier. Reusing space for other variables could be a performance benefit, but since we're talking local variables I doubt it will have any real effect at all. Space for all local variables in a method is allocated on the stack in one step upon method entry, and released in one step upon method exit. I don't think it really matters how many different variables there are om that stack; the allocation takes the same amount of time.

The only case I can think of where the amount of stack usage really matters is if the method is in a deep recursion. In this case the amount of stack space used per recursive call affects how deeply you can recurse before throwing an error. Usually in my experience this is a non-issue, as most recursive calls either get nowhere near the depth required to throw an error, or they recurse infinitely - in which case it doesn't really matter what the maximum depth is; you're going to error eventually. However there are some applications which require recursion which is finite but very deep; in these cases, minimizing stack usage does become important, and minimizing variable scope can help you do that.

But to repeat for Rusty's benefit: when considering pros and cons of minimizing scope (errr... actually just pros it seems): the performance benefits are almost always secondary (or tertiary) to the benefits to readability and catching errors.
[ March 28, 2006: Message edited by: Jim Yingst ]
 
Paul Clapham
Marshal
Posts: 28177
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Rusty Shackleford:
Because doing something that is not necessary is never something you should do. Regardless of whether it is legal or has no adverse effects on a program.

Flip it around, what does redeclaring a variable inside a loop buy you? If the answer is nothing(and it is), then there is no reason to do it. Do that in an academic assignment or real world code at your job and see what it buys you.

I still don't get it. It is necessary to declare the variable. Is it necessary to declare it inside the loop? No, I admit it isn't. But is it necessary to declare it outside the loop? No, I don't think it is. As far as I can see it works either way. So I'm not following your statement that something isn't necessary.

Oh, wait a minute. You said "what does redeclaring a variable inside a loop buy you?" Well, I don't know. Normally the compiler doesn't let me do that. But in any case there's no redeclaring going on in the code we're discussing.

And I declare variables inside my loops all the time here at my real-world job. It buys me code that works and can be understood.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jim Yingst:
I don't think it really matters how many different variables there are om that stack; the allocation takes the same amount of time.

The only case I can think of where the amount of stack usage really matters is if the method is in a deep recursion.



Full agreement!
 
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is another alternative that minimizes the scope of the variable to the for loop and avoids redeclaring the variable:

Declare sum in the initialization portion of the for loop:



I would argue that this is slightly less readable than either of the two versions Arun posted, but it does solve the scope and redeclaration issues.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Scott Johnson:

I would argue that this is slightly less readable than either of the two versions Arun posted, but it does solve the scope and redeclaration issues.



If redeclaration was an issue, that is...
[ March 29, 2006: Message edited by: Ilja Preuss ]
 
Ranch Hand
Posts: 1923
Scala Postgres Database Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Declare sum in the initialization portion of the for loop:



It's not only a declaration, but also an assignment.
Sum is assigned a value which is never read - why?

I agree that this is less readable.

If you fear reassignments, eliminate sum:

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic