In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how to avoid creating unnecessary objects in Java. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Brief introduction
In Java development, programmers should avoid creating objects with the same function as much as possible, because this not only consumes memory, but also affects the running speed of the program. In this case, consider reusing the object.
Next, we will give examples of several scenarios in which objects are reused to see if we have been tricked. If we quickly change it quietly before it is discovered, it will be diss if it is found!
1. String and Boolean
There seems to be no difference between the following two ways of writing, but if we delve into the bottom of jvm, we can take advantage of the characteristics of the jvm runtime pool to avoid creating String objects with the same functionality (especially inside the loop), which can lead to considerable performance optimization and memory savings.
Erroneous writing
/ / A new String object is created every time, and the constant pool String name2 = new String ("plum") is not added.
Correct writing method
/ / write String name1 = "plum" correctly
In addition, programmers who have just written Java code should also correctly choose the use of String, StringBuilder, and StringBuffer classes. String is an immutable object, which is usually used to define immutable strings; StringBuilder and StringBuffer are used for variable string manipulation scenarios, such as string concatenation; and StringBuffer is thread-safe, which uses the Synchronized keyword to achieve thread synchronization.
/ / append () method public synchronized StringBuffer append (String str) {toStringCache = null; super.append (str) in StringBuffer; append () method public StringBuilder append (String str) {super.append (str); return this;} in return this;} / / StringBuilder
Boolean is a commonly used type, and you should also use Boolean.valueof () instead of new Boolean () in development. As you can see from the source code of Boolean, the Boolean class defines two properties of final static, while Boolean.valueof () directly returns these two 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 unpacking and packing
Java provides automatic unpacking and boxing of basic data types, does that mean we can use these two types in our code at will? In fact, there is no problem at the code level in theory, 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); 使用Integer耗时3毫秒Long start = System.currentTimeMillis (); / / modify Integer to int int sum = 0 for (int I = 0; I)
< 100000; i++) { sum += i;}System.out.println(System.currentTimeMillis() - start); 使用int耗时0毫秒 因此关于自动拆箱装箱的使用,我们其实也可以做适当的考虑,毕竟有时候代码性能就是一点点挤出来的嘛!!! 3、正则表达式 正则表达式我们经常用于字符串是否合法的校验,我们先来看一段简单的代码(大家有没有一眼看出问题呢?我想你肯定看出来了!!!): 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);} 执行这段代码的时间,一共耗时71毫秒,看似好像挺快的!But we do a very simple optimization, and 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; iTunes +) {/ / email.matches (regex); pattern.matcher (email);} System.out.println (System.currentTimeMillis ()-start);}
It takes 1 millisecond to execute the code again, which is 70 times faster!
This is because the String.matches () method needs to execute Pattern.compile (regex) every time it is created in a loop, and it is expensive to create an instance of Patter because the regular expression needs to be compiled into a finite state machine (finite state machine). We often ignore the high performance because Java api provides more convenient method calls, and it is often not easy to find.
This is the end of this article on "how to avoid creating unnecessary objects in Java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.