This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
- Prepare for spring recruitment or summer internship in 2022, wish you every day a hundred million points of progress! Day1
- This article summarizes how to avoid creating unnecessary objects in Java. It will be updated daily
- About “Redis entry to master”, “concurrent programming” and other knowledge points can refer to my previous blog: XXX
- Believe in yourself, the more live more strong, alive should be open, meet water bridge! Life, you give me pressure, I return you miracle!
Introduction to the
In Java development, programmers should avoid creating objects with the same function as possible, because this will consume memory and slow down the program. Consider reusing objects in this case.
Next examples of several object reuse scenarios, to see if we are not in the trick, if there is a hurry while still not found quietly change, was found will be diss!
String and Boolean
There may seem to be no difference between the two, but if we look deep into the JVM, we can take advantage of the JVM’s runtime constant pool features to avoid creating strings with the same functionality (especially inside loops), which can lead to significant performance optimizations and memory savings.
Error writing
// a new String is created each time and is not added to the constant pool. String name2 = new String(" Plum EIGHT ");Copy the code
Correct term
// String name1 = "Plum EIGHT ";Copy the code
In addition, programmers who are just writing Java code should also use the String, StringBuilder, and StringBuffer classes correctly. String is an immutable object and is usually used to define immutable strings. StringBuilder and StringBuffer are used for variable string operation scenarios, such as string concatenation. StringBuffer is thread-safe and synchronizes threads with the Synchronized keyword.
Public synchronized StringBuffer append(String STR) {toStringCache = null; super.append(str); return this; } public StringBuilder appEnd (String STR) {super.append(STR); return this; }Copy the code
The Boolean class defines two final static properties. The Boolean class defines two final static properties. The Boolean class defines two final static properties. Boolean. Valueof () directly returns the two defined attributes, while new Boolean() creates a new object.
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
Copy the code
2, automatic unpacking and packing
Java provides automatic unboxing and boxing for primitive data types. Does that mean we can use them in our code at will? In fact, there is no problem at the code level in theory, but there is room for specific performance optimization!!
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);
Copy the code
Using Integer takes 3 milliseconds
long start = System.currentTimeMillis(); Int sum = 0; for (int i = 0; i < 100000; i++) { sum += i; } System.out.println(System.currentTimeMillis() - start);Copy the code
Using int takes 0 ms
Therefore, regarding the use of automatic unboxing, we can also do appropriate consideration, after all, sometimes the code performance is a little bit of extrusion!!
3. Regular expressions
Regular expressions are often used to check whether a string is valid. Let’s start with a simple piece of code. I’m sure you can see that!!) :
public static void main(String[] args) { String email = "[email protected]"; 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); }Copy the code
This code takes 71 milliseconds to execute, which seems like a lot of time!
But let’s make a very simple optimization, and the optimized code looks like this:
public static void main(String[] args) { String email = "[email protected]"; 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); }Copy the code
Executing the code again took a total of 1 millisecond, 70 times faster.
This is because the string.matches () method needs to execute pattern.pile (regex) each time it is created in the loop, and the cost of creating a Patter instance is high, This is because you need to compile the regular expression into a Finite State machine. This is often overlooked for performance considerations because Java apis provide easy method calls, and is often not easy to detect. This time you need to be excellent, to “chew the words”!
“Welcome to the discussion in the comments section. The excavation authorities will draw 100 nuggets in the comments section after project Diggnation. See the event article for details.”