Write high-quality code: 151 recommendations for improving Java programs--[52~64]

Source: Internet
Author: User
Tags collator stringbuffer

Write high-quality code: 151 recommendations for improving Java programs--[52~64] recommended use of String direct value assignment

Java in order to avoid a large number of string objects in a system (why a large number of production, because the string string is the most commonly used in the program), so the design of a string pool (also known as a string constant pool, string pool or string Constant Pool or string Literal pool), where a string string object is accommodated in a pool of strings, it is created in such a way that when a string is created, it first checks if there is a string of equal literal value in the pool, and if so, it is no longer created, directly returning a reference to that object in the pool. If not, create it and put it in the pool and return a reference to the new object, which is very close to what we normally call a pool. For this example, when you create the first "James" string, check that there is no object in the string pool, find it, and then create the string "James" and put it in the pool, when the STR2 string is created, because the string is already in the pool, the reference to the object is returned directly, STR1 and str2 point to the same address, so use "= =" to determine that it is of course equal.

public class Client58 {    public static void main(String[] args) {        //建议        String str1 = "詹姆斯";        //建议        String str2 = "詹姆斯";        //不建议,直接声明一个String对象是不检查字符串池的,也不会把对象放到字符串池中        String str3 = new String("詹姆斯");        String str4 = str3.intern();        // 两个直接量是否相等        System.out.println(str1 == str2);        // 直接量和对象是否相等        System.out.println(str1 == str3);        // 经过intern处理后的对象与直接量是否相等,        //intern会检查当前对象在对象池中是否存在字面值相同的引用对象,如果有则返回池中的对象,如果没有则放置到对象池中,并返回当前对象。        System.out.println(str1 == str4);    }}
Use String, StringBuffer, StringBuilder correctly

Use the scenario of the String class: String classes can be used in scenes where the strings do not change frequently, such as declarations of constants, small amounts of variable operations, and so on;
Using the StringBuffer scenario: with frequent string operations (such as stitching, replacing, deleting, etc.) and running in multithreaded environments, you might consider using StringBuffer, such as XML parsing, HTTP parameter parsing, and encapsulation.
Using the StringBuilder scenario: with frequent string operations (such as stitching, replacing, deleting, etc.) and running in a single-threaded environment, consider using StringBuilder, such as the concatenation of SQL statements, JSON encapsulation, and so on.

Performance comparison:
StringBuffer and StringBuilder are basically the same, are variable character sequences, the difference is: StringBuffer is thread-safe, StringBuilder is thread insecure, turn over the source code of both, You will find that there are keyword syschronized before the StringBuffer method, which is why StringBuffer is far below StringBuffer in performance.
In terms of performance, because the operation of the string class is the object that produces a string, and StringBuilder and StringBuffer are only a single character array, the operation of the string class is much slower than the StringBuffer and StringBuilder.

It is strongly recommended to use UTF encoding to sort Chinese characters using the Collator class

If the sort object is a commonly used Chinese character, the use of collator class sorting can meet our requirements, after all, GB2312 already contains most of the Chinese characters, if you need to strictly sort, you have to use some open source projects to achieve their own, such as pinyin4j can convert Chinese characters to pinyin, Then we implement the sorting algorithm by ourselves, but at this point you will find many problems such as algorithms, Polyphone, and so on.

import java.text.Collator;import java.util.Arrays;import java.util.Comparator;import java.util.Locale;public class CollatorDemo {    public static void main(String[] args) {        String[] strs = { "张三(Z)", "李四(L)", "王五(W)" };        //定义一个中文排序器        Comparator c = Collator.getInstance(Locale.CHINA);        Arrays.sort(strs,c);        int i = 0;        for (String str : strs) {            System.out.println((++i) + "、" + str);        }    }}

Results:
1, John Doe (L)
2, Harry (W)
3, Zhang San (Z)

Use arrays instead of collections in scenarios with high performance requirements

When a base type is summed, the efficiency of the array is 10 times times that of the set.

//对数组求和    public static int sum(int datas[]) {        int sum = 0;        for (int i = 0; i < datas.length; i++) {            sum += datas[i];        }        return sum;    }
// 对列表求和计算    public static int sum(List<Integer> datas) {        int sum = 0;        for (int i = 0; i < datas.size(); i++) {            sum += datas.get(i);        }        return sum;    }

The basic type is in the stack memory operation, and the object is the heap in memory operations, the characteristics of the stack memory is: fast, small capacity, heap memory is characterized by: slow speed, large capacity (from the performance of the basic type of processing dominant). Second, when the summation operation (or other traversal calculation) to do the unpacking action, so the unnecessary performance consumption is produced.

If necessary, use a variable-length array
public static <T> T[] expandCapacity(T[] datas, int newLen) {        // 不能是负值        newLen = newLen < 0 ? 0 : newLen;        // 生成一个新数组,并拷贝原值        return Arrays.copyOf(datas, newLen);    }
  public static void main(String[] args) {        //一个班级最多容纳60个学生        Stu [] stuNums= new Stu[60];        //stuNums初始化......        //偶尔一个班级可以容纳80人,数组加长        stuNums=expandCapacity(stuNums,80);        /* 重新初始化超过限额的20人...... */            }
Specify the initial capacity for the collection in a clear scenario

ArrayList (): default constructor that provides an empty list with an initial capacity of 10.
ArrayList (int initialcapacity): Constructs an empty list with the specified initial capacity.
ArrayList (collection<? extends e> c): Constructs a list of elements that contain the specified Collection, arranged in the order in which they are returned by the Collection iterator.

From here we can see that if the initial capacity is not set, the system will be expanded by 1.5 times times the rule, each expansion is a copy of the array, if the volume of data is large, such copies will be very resource-intensive and inefficient. So, if we know the possible length of a ArrayList, then setting an initial capacity on ArrayList can significantly improve system performance.

Write high-quality code: 151 recommendations for improving Java programs--[52~64]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.