How to optimize Java code and what practical tips are available at work?
1. Minimize the visibility of class members and methods
Example:If it is a private method, delete it if you want to delete it
If a The
service method of public
, or a public member variable, should be deleted without thinking too much.
2. Use displacement operations instead of multiplication and division
Computers use binary representation, and displacement operations will greatly improve performance.
> Right shift is equivalent to dividing by 2;
>>> Unsigned right shift is equivalent to dividing by 2, but it will ignore the sign bit and fill the empty bits with 0s.
a = val << 3; b = val >> 1;
3. Minimize repeated calculations of variables
We know that calling methods is costly, including creating stack frames, protecting the scene when calling methods, restoring the scene, etc.
//反例 for (int i = 0; i < list.size(); i++) { System.out.println("result"); } //正例 for (int i = 0, length = list.size(); i < length; i++) { System.out.println("result"); }
When list.size()
is very large, it reduces a lot of consumption.
4. Do not catch RuntimeException
RuntimeException should not be caught through catch statements, but should be avoided by coding means.
As shown in the following code, an array out-of-bounds exception may occur in the list.
Whether it is out of bounds can be judged in advance through the code, instead of waiting to catch an exception when it occurs.
Judge this way in advance, the code will be more elegant and efficient.
public String test1(List<String> list, int index) { try { return list.get(index); } catch (IndexOutOfBoundsException ex) { return null; } } //正例 public String test2(List<String> list, int index) { if (index >= list.size() || index < 0) { return null; } return list.get(index); }
5. Use local variables to avoid allocation on the heap
Since heap resources are shared by multiple threads and are the main area where the garbage collector works, too many objects will cause GC pressure. , variables can be allocated on the stack through local variables. In this way, the variables will be destroyed when the method execution is completed, which can reduce the pressure on the GC.
6. Reduce the scope of variables
Pay attention to the scope of variables and minimize the creation of objects.
As shown in the following code, the variable s will be created every time the method is entered, and it can be moved inside the if statement.
public void test(String str) { final int s = 100; if (!StringUtils.isEmpty(str)) { int result = s * s; } }
7. Lazy loading strategy
Try to adopt the lazy loading strategy and only create it when needed
String str = "月伴飞鱼"; if (name == "公众号") { list.add(str); } if (name == "公众号") { String str = "月伴飞鱼"; list.add(str); }
8. Access static variables directly using the class name
Use objects to access static variables. This method adds one more addressing operation. You need to first find the class corresponding to the variable, and then find the variable corresponding to the class.
// 反例 int i = objectA.staticMethod(); // 正例 int i = ClassA.staticMethod();
9. Use StringBuilder for string splicing
For string splicing, use StringBuilder or StringBuffer, do not use numbers.
//反例 public class StringTest { @Test public void testStringPlus() { String str = "111"; str += "222"; str += "333"; System.out.println(str); } } //正例 public class TestMain { public static void main(String[] args) { StringBuilder sb = new StringBuilder("111"); sb.append("222"); sb.append(333); System.out.println(sb.toString()); } }
10. Rewrite the HashCode of the object
Rewrite the HashCode of the object, do not simply return a fixed value
Some students are developing overriding HashCode and Equals methods, Will return the value of HashCode to a fixed 0, and this is inappropriate
When these objects are stored in HashMap, the performance will be very low, because HashMap locates the Hash slot through HashCode, and there is a conflict. Only when this happens, linked lists or red-black trees are used to organize nodes, and 0 is returned fixedly, which is equivalent to invalidating the Hash addressing function.
11. Initialization of collections such as HashMap
When initializing collections such as HashMap, specify the initial value size
There are many such objects, such as ArrayList, StringBuilder, etc., by specifying the initial value The value size can reduce the performance loss caused by expansion.
Calculation of initial value size:
12. Create object reference inside the loop
Inside the loop Do not continuously create object references
//反例 for (int i = 1; i <= size; i++) { Object obj = new Object(); } //正例 Object obj = null; for (int i = 0; i <= size; i++) { obj = new Object(); }
The first method will cause size Object object references to exist in the memory. If the size is large, memory will be consumed
13. Traverse the Map using EntrySet method
Using the EntrySet method, you can directly return the set object, which can be used directly; and using the KeySet method, you get a collection of keys, and you need to perform another get operation, which adds one more operation step. Therefore, it is more recommended to use the EntrySet method to traverse the Map.
Set<Map.Entry<String, String>> entryseSet = nmap.entrySet(); for (Map.Entry<String, String> entry : entryseSet) { System.out.println(entry.getKey()+","+entry.getValue()); }
14. Do not use the same Random in multiple threads
The seeds of the Random class will compete during concurrent access, resulting in reduced performance. It is recommended to use ThreadLocalRandom in a multi-threaded environment. kind.
public static void main(String[] args) { ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current(); Thread thread1 = new Thread(()->{ for (int i=0;i<10;i++){ System.out.println("Thread1:"+threadLocalRandom.nextInt(10)); } }); Thread thread2 = new Thread(()->{ for (int i=0;i<10;i++){ System.out.println("Thread2:"+threadLocalRandom.nextInt(10)); } }); thread1.start(); thread2.start(); }
15. It is recommended to use LongAddr for auto-increment
Auto-increment operation can control thread safety through the combination of synchronized
and volatile
, or you can Use an atomic class (such as AtomicLong).
The speed of the latter is higher than the former, AtomicLong
Using CAS for comparison and replacement will cause too many invalid spins when there are many threads. You can use LongAdder to replace AtomicLong for further progress. performance improvement.
public class Test { public int longAdderTest(Blackhole blackhole) throws InterruptedException { LongAdder longAdder = new LongAdder(); for (int i = 0; i < 1024; i++) { longAdder.add(1); } return longAdder.intValue(); } }
16. Use less reflection in programs
The reflection function is very powerful, but it is implemented by parsing bytecode, and the performance is not very ideal.
In reality, there are many optimization methods for reflection, such as caching the reflection execution process (such as Method) and using multiplexing to speed up reflection.
After Java 7.0, a new package java.lang.invoke
was added, and a new JVM bytecode instruction invokedynamic was added to support directly passing strings from the JVM level Make a call to the target method.
The above is the detailed content of How to optimize Java code and what practical tips are available at work?. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
