Home arrow static arrow Java Programming [Archive] - narrow scope vs. efficiency
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - narrow scope vs. efficiency
This topic has 5 replies on 1 page.

Posts:835
Registered: 2/12/01
narrow scope vs. efficiency  
Jun 20, 2004 8:36 AM



 
narrow scope:for (cond) {  byte[] buf = new byte[const];  in.read(buf);  out.write(buf);}vs. efficiency:byte[] buf = new byte[const];for (cond) {  in.read(buf);  out.write(buf);}

What do you prefere? Do you use a profiler to make the decision?
 

Posts:5,965
Registered: 5/17/03
Re: narrow scope vs. efficiency  
Jun 20, 2004 10:02 AM (reply 1 of 5)



 
I prefer efficiency. You still can declare buf in a narrow scope like this,
{   byte[] buf = new byte[const];   for (cond) {      in.read(buf);      out.write(buf);   }}
 

Posts:5,965
Registered: 5/17/03
Re: narrow scope vs. efficiency  
Jun 20, 2004 10:14 AM (reply 2 of 5)



 
I would also consider using a while-loop. The intended use of a for-loop is to iterate through a sequence of values which doesn't seem to be the case here.
 

Posts:835
Registered: 2/12/01
Re: narrow scope vs. efficiency  
Jun 20, 2004 10:30 AM (reply 3 of 5)



 
{  byte[] buf = new byte[const];  for (cond) {    in.read(buf);    out.write(buf);  }}


But what about if buf is used throughout the procedure (locally). It should then be declared at the class scope for efficiency. You'll not be able to link the buf to the method by "{}".
 

Posts:5,965
Registered: 5/17/03
Re: narrow scope vs. efficiency  
Jun 20, 2004 10:47 AM (reply 4 of 5)



 
But what about if buf is used throughout the procedure
(locally). It should then be declared at the class
scope for efficiency. You'll not be able to link the
buf to the method by "{}".

In the choise between class or method scope I probably would declare buf in the method scope. At least if the method isn't called very often. You'll have to use common sense. On one hand you want an as narrow scope as possible but on the other hand a narrow scope cannot motivate the creation of zillions of objects in an innermost loop.
 

Posts:1,183
Registered: 1/23/02
Re: narrow scope vs. efficiency  
Jun 20, 2004 1:42 PM (reply 5 of 5)



 
I prefer efficiency.

[UlrikaJ] is the root of all evil. - Donald Knuth
 
This topic has 5 replies on 1 page.