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
##
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
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!
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! ! !
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!

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

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.

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

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

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.

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

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.
