optimizing the java code

Some tips of Optimizing the code。

This blog is about some tips of how to optimizing the java code,I will write down some principles or some code about this.

  • Don't initialize the object in a loop
  • Avoid String concatenation in a loop
  • Use StringBuilder to build a large String

Use System.arraycopy

usually,we copy the array using a loop like this:

int[] copy = new int [length];

for(int i=0;i<length;i++)

{

 copy [i] = array[i];

}

and you can use the System.arraycopy to do the same thing:

int length = array.length;

int[] copy = new int [length];

System.arraycopy(array, 0, copy, 0, length);


Using System.arraycopy is faster than copy a array in a loop

About I/O Streams

First thing to remember is closing streams,the best way to do this is in a finally block.
Second,Buffering,the BufferedInputStream stores all the bytes that the FileInputStream sends until it reaches its limit,the default limit is 512 bytes.

try{

                          InputStream in = new FileInputStream(fileFrom);

                          inBuffer = new BufferedInputStream(in);

                          OutputStream out = new FileOutputStream(fileTo);

                          outBuffer = new BufferedOutputStream(out);

                          while(true){

                                          int bytedata = inBuffer.read();

                                          if(bytedata == -1)

                                          break;

                                          out.write(bytedata);

                          }

             }

             finally{

              if(inBuffer != null)

                          inBuffer.close();

              if(outBuffer !=null)

                          outBuffer.close();

             }

a better way is to use the method available() to define the size of the byte array.

 try{

                          in = new FileInputStream(fileFrom);

                          out = new FileOutputStream(fileTo);

                          int availableLength = in.available();

                          byte[] totalBytes = new byte[availableLength];

                          int bytedata = in.read(totalBytes);

                          out.write(totalBytes);

                            

             }

             finally{

              if(in != null)

                          in.close();

              if(out !=null)

                          out.close();

             }