1Why should you avoid excessive String concatenation using t
1.Why should you avoid excessive String concatenation using the + operator?
2. A class or object is a better representation of data than parallel arrays. Why?
Solution
1.For concatenating two strings, the \'+\' operator will probably have less overhead, but as you concatenate more strings, the StringBuffer will come out ahead, using fewer memory allocations, and less copying of data.
To concatenate two strings using \'+\', a new string needs to be allocated with space for both strings, and then the data copied over from both strings. A StringBuffer is optimized for concatenating, and allocates more space than needed initially. When you concatenate a new string, in most cases, the characters can simply be copied to the end of the existing string buffer.
for example:
String s = \"\";
for (int i = 0; i < 10; i++) {
s = s + Integer.toString(i);
}
Using string in this loop will generate 10 intermediate string objects in memory: \"0\", \"01\", \"012\" and so on. On Other side using StringBuffer you simply update some internal buffer of StringBuffer and you do not create those intermediate string objects that you do not need:
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 10; i++) {
sb.append(i);
}
2.
In the parallel arrays approach, each record is broken down into its component fields, and arrays are assembled for each field across the collection. For example, consider a book store keeping track of purchases, where for each purchase the name of the book,price, and day of the week the purchase was made are recorded. The data would be stored in 3 arrays, one each for names, prices, and days. All arrays would be of the same length, equal to the total number of purchases.
In contrast, in the array of objects approach, a class is defined describing the information associated with one record. Then the collection of records can be represented as an array of objects of the record class. In the book store example, a \"Book\" class can be defined, containing a field each for book name, price, and day. The entire store data is an array of Book objects, with one object for each purchase.
Arrays of objects are clearly more consistent with object-oriented programming concepts and the code is typically more elegant.
