Which of the following 2 methods executes faster ?class Trial { String _member; void method1() { for(int i=0;i<2048;i++) { _member += "test"; } } void method2() { String temp; for(int i=0;i<2048;i++) { temp += "test"; } _member = temp; } } (a) method1() (b) method2() (c) Both method1() and method2() takes same time for execution

(b)

Accessing method variables requires less overhead than accessing class variables.

  
Showing Answers 1 - 2 of 2 Answers

Amit

  • Apr 27th, 2005
 

a

  Was this answer useful?  Yes

chandra

  • Jun 19th, 2005
 


 
Time taken for method1() is 1375 
Time taken for method2()is 1406 
 
public static void main(String arg[]) 

Class_Method_Variable cmv=new Class_Method_Variable(); 
Date d=new Date(); 
long t1=d.getTime(); 
cmv.method1(); 
Date d1=new Date(); 
long t2=d1.getTime(); 
long time=t2-t1; 
 
System.out.println("Time taken for method1() is "+time); 
Date d3=new Date(); 
t1=d3.getTime(); 
cmv.method2(); 
Date d4=new Date(); 
t2=d4.getTime(); 
time=t2-t1; 
System.out.println("Time taken for method2()is "+time); 
 
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions