Home  >  Article  >  Java  >  How to avoid unnecessary object creation in Java?

How to avoid unnecessary object creation in Java?

PHPz
PHPzforward
2023-04-24 22:31:051524browse

Introduction

In Java development, programmers should try their best to avoid creating objects with the same functions, because this not only consumes memory, but also affects the running speed of the program. Consider reusing objects in this case.

Next, we will give some examples of scenarios where objects are reused to see if we have been tricked. If so, we should quickly change it quietly before it is discovered. If we are discovered, we will be dissed!

1, String and Boolean

There seems to be no difference between the following two ways of writing, but if we understand the underlying jvm deeply, we can use the characteristics of the jvm runtime constant pool to avoid creating String objects with the same functionality (especially created inside loops) can bring considerable performance optimization and memory savings.

Wrong way of writing

// 每次都会创建一个新的String对象,且不会加入常量池
String name2 = new String("李子捌");

Correct way of writing

// 正确写法
String name1 = "李子捌";

In addition, programmers who have just written Java code must also correctly choose the String, StringBuilder, and StringBuffer classes use. String is an immutable object and is usually used to define immutable strings; StringBuilder and StringBuffer are used in variable string operation scenarios, such as string splicing; StringBuffer is thread-safe and uses the Synchronized keyword to achieve thread synchronization.

// StringBuffer中的append()方法
public synchronized StringBuffer append(String str) {
    toStringCache = null;
    super.append(str);
    return this;
}

// StringBuilder中的append()方法
public StringBuilder append(String str) {
    super.append(str);
    return this;
}

Boolean is a commonly used type. In development, Boolean.valueof() should also be used instead of new Boolean(). As can be seen from the source code of Boolean, the Boolean class defines two final static properties. Boolean.valueof() directly returns the two defined properties, while new Boolean() creates a new object.

public static final Boolean TRUE = new Boolean(true);

public static final Boolean FALSE = new Boolean(false);

2. Automatic unboxing and boxing

Java provides automatic unboxing and boxing functions for basic data types. Does that mean we can do whatever we want in the code? What about the use of these two types? In fact, in theory, there is no problem at the code level, but there is still room for optimization in terms of specific performance! ! !

Let’s test the performance

long start = System.currentTimeMillis();
Integer sum = 0;
for (int i = 0; i < 100000; i++) {
    sum += i;
}
System.out.println(System.currentTimeMillis() - start);

Using Integer takes 3 milliseconds

How to avoid unnecessary object creation in Java?##

long start = System.currentTimeMillis();
// 修改Integer 为 int 
int sum = 0;
for (int i = 0; i < 100000; i++) {
    sum += i;
}
System.out.println(System.currentTimeMillis() - start);

Using int takes 0 milliseconds

How to avoid unnecessary object creation in Java?

So regarding the use of automatic unboxing and boxing, we can actually make appropriate considerations. After all, sometimes code performance is squeezed out little by little! ! !

3. Regular expressions


Regular expressions are often used to verify whether strings are legal. Let’s first look at a simple code (do you see it at a glance? What’s the problem? I think you must have figured it out!!!):

public static void main(String[] args) {

    String email = "1057301174@qq.com";
    String regex = "^([a-z0-9A-Z]+[-|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$";

    long start = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++) {
        email.matches(regex);
    }

    System.out.println(System.currentTimeMillis() - start);

}

The execution time of this code took a total of 71 milliseconds, which seems to be quite fast!

How to avoid unnecessary object creation in Java?

But let’s do a very simple optimization. The optimized code is as follows:

public static void main(String[] args) {

    String email = "1057301174@qq.com";
    String regex = "^([a-z0-9A-Z]+[-|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$";
    Pattern pattern = Pattern.compile(regex);

    long start = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++) {
        //email.matches(regex);
        pattern.matcher(email);
    }

    System.out.println(System.currentTimeMillis() - start);

}

Execute the code again, which takes 1 millisecond in total. Fast 70 times more! ! !

How to avoid unnecessary object creation in Java?

This is because when the String.matches() method is created in a loop, Pattern.compile(regex) needs to be executed every time, and the cost of creating a Patter instance is high , because the regular expression needs to be compiled into a finite state machine. In this case, we often ignore performance considerations because the Java API provides more convenient method calls, and it is often not easy to find.

The above is the detailed content of How to avoid unnecessary object creation in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete