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!

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools
