java - What is purpose of closing BufferedReader class? Does it affect time / memory (if how)? -


codeforces contest 355 q_a blackhorse21

public class a_vanyaandfence { public static void main(string args[])throws ioexception{     bufferedreader br=new bufferedreader(new inputstreamreader(system.in));     stringtokenizer st=new stringtokenizer(br.readline());     int n,h;     n=integer.parseint(st.nexttoken());     h=integer.parseint(st.nexttoken());     st=new stringtokenizer(br.readline());     //int arr[]=new int[n];     int cnt=0;     for(int i=0;i<n;i++){         int a=integer.parseint(st.nexttoken());         if(a>h){             cnt+=2;         }         else             cnt++;     }     system.out.println(cnt); } 

this code took 155ms,20100 kb

public class a_vanyaandfence { public static void main(string args[])throws ioexception{     bufferedreader br=new bufferedreader(new inputstreamreader(system.in));     stringtokenizer st=new stringtokenizer(br.readline());     int n,h;     n=integer.parseint(st.nexttoken());     h=integer.parseint(st.nexttoken());     st=new stringtokenizer(br.readline());     //int arr[]=new int[n];     int cnt=0;     for(int i=0;i<n;i++){         int a=integer.parseint(st.nexttoken());         if(a>h){             cnt+=2;         }         else             cnt++;     }     system.out.println(cnt);     br.close(); } 

}

this code took 124ms,20100 kb

why?

even though impact might not significant, when text being read not extensive. there has impact on memory primarily, , time secondarily, when text being read massive. close() method not closes stream, releases system resources associated bufferreader / reader class implementation.

file descriptor resource in operating system, released once close() called on bufferreader . in latest versions of java, garbage collector runs every , then, , should call close() mehtod , dispose off abandoned file descriptor. untill then, poor guy hanging around corner.

lets initializing bufferreader objects inside large loop, , not closing same within loop. loop might pick abandoned file descriptors before garbage collector job. programming practice because once stream has been closed, other bufferreader / reader methods through ioexceptions (another close() method nothing).

ref: https://docs.oracle.com/javase/7/docs/api/java/io/bufferedreader.html#close()

that being said, myself worked on extensive project closing bufferreader each instance became difficult, , did avoid on several occasions. didn’t have impact worth noticing on output , program execution. bufferreader objects discarded garbage collector. real world applications may satisfied performance of garbage collection , not show significant impact in terms of time , memory.

hope helps.