search
HomeJavajavaTutorialHow to avoid unnecessary object creation in Java?

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:亿速云. If there is any infringement, please contact admin@php.cn delete
Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Java Features for Modern Development: A Practical OverviewJava Features for Modern Development: A Practical OverviewMay 08, 2025 am 12:12 AM

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

Mastering Java: Understanding Its Core Features and CapabilitiesMastering Java: Understanding Its Core Features and CapabilitiesMay 07, 2025 pm 06:49 PM

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Can Java be run everywhere?Can Java be run everywhere?May 07, 2025 pm 06:41 PM

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

What is the difference between JDK and JVM?What is the difference between JDK and JVM?May 07, 2025 pm 05:21 PM

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Java features: a quick guideJava features: a quick guideMay 07, 2025 pm 05:17 PM

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.