Code Optimization : Effect of String concatenation on performance

Motivation

  • We always wanted to write the most efficient piece of code that will do the job.

  • Same code with string concatenation took : 10ms

  • Without String concatenation code took : 3ms

With String concetenation : took 10ms

import java.util.*;
public class index {
        public static void main(String args[]) {
            List<Employee> FinalObject = new ArrayList<>();
            //list of size 10k
            List<Integer> parentList= new ArrayList<>();

            for(int i=0;i<10000;i++) {
                parentList.add(i+1);
            }

            // traverse the parent list and then creating object for each element and then adding each object to new list

            int parentListSize=parentList.size();
            long starttime=System.currentTimeMillis();
            //TODO : this piece i need to divide into multiple threads so that each thread is processing part of it
            for(int i=0;i<parentListSize;i++) {

                Employee e1=new Employee();
                e1.setId(i);
                e1.setName(i+ "test name");    //string concetenatoin 
                e1.setDep(i+ "test department"); // string concetenation
                FinalObject.add(e1);

//if we remove the concetenation performance time just dropped like crazy 
            }

            System.out.println("Time Taken to complete the traversing and addition is  "+(System.currentTimeMillis()-starttime));


            //checking whether everything inserted in the final list or not
            //ok this is working
//            int FinalObjectListSize=FinalObject.size();
//            for(int i=0;i<FinalObjectListSize;i++) {
//                System.out.println("Employee Id  :  "+ FinalObject.get(i).getId());
//            }

        }


    }
    class Employee {

        private int id;
        private String name;
        private String dep;
        Employee() {
        }

        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id=id;
        }
        public void setName(String name){
            this.name=name;
        }
        public void setDep(String dep) {
            this.dep=dep;
        }

    }