当前位置:网站首页>String since I can perform performance tuning, I can call an expert directly
String since I can perform performance tuning, I can call an expert directly
2022-06-25 20:00:00 【Code byte】
Margo ,String What else can you optimize ? Do you frame me ?
Mo panic , Today I'll show you something different String, Pinch it from the root to G spot .
And code brother shares an example : Through performance tuning, we can easily store tens of megabytes of memory G data .
String
The object is that we all 「 feel 」 Object type of , But we always ignore her performance problems .
Love her , You can't just play together , To understand String
Deep inside , Make one 「 A tiger in the heart , Sniff rose 」 Warm man .
Through the following analysis , We opened her clothes step by step , Go deep inside , Upgrade one Level, Give Way String
Take off directly :
- Properties of string objects ;
- String The immutability of ;
- Big string construction skills ;
- String.intern Save memory ;
- String segmentation techniques ;
String Body decryption
Want to know more about , Let's start with the basic composition ……
「String The creator 」 Yes String
Objects are heavily optimized to save memory , Thus enhance String Performance of :
Java 6 And before
The data is stored in char[]
Array ,String
adopt offset
and count
Two properties are located char[]
Data acquisition string .
This can efficiently and quickly locate and share array objects , And save memory , But it may lead to memory leakage .
share char Why can arrays cause memory leaks ?
String(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = count;}public String substring(int beginIndex, int endIndex) { //check boundary return new String(offset + beginIndex, endIndex - beginIndex, value);}
call substring()
While creating a new string , But the value of the string value
It still points to... In memory The same array , As shown in the figure below :
If we just use substring
Get a short character , And the original string
When the string is very large ,substring If the object is always referenced .
here String
Strings cannot be recycled , Resulting in memory leaks .
If there are a large number of such passes substring Get a short string in a super large string , It will cause memory overflow due to memory leakage .
JDK7、8
Removed offset
and count
Two variables , Less String Object footprint .
substring Source code :
public String(char value[], int offset, int count) { this.value = Arrays.copyOfRange(value, offset, offset + count);}public String substring(int beginIndex, int endIndex) { int subLen = endIndex - beginIndex; return new String(value, beginIndex, subLen);}
substring()
adopt new String()
A new string object is returned , When creating a new object, you can use Arrays.copyOfRange()
Deep copy a new character array .
As shown in the figure below :
String.substring Methods are no longer shared char[]
Array data , Solved the problem of possible memory leakage .
Java 9
take char[]
Change the field to byte[]
, newly added coder
attribute .
Margo , Why do you change that ?
One char The characters occupy 2 Bytes ,16 position . Store characters in single byte encoding ( A character occupying one byte ) It seems very wasteful .
To save memory space , So I used 1 Bytes 8 Bit byte Array to hold strings .
The goddess of thrift , Who doesn't love ……
new property coder The role of is : In calculating string length or using indexOf()
When the method is used , We need to calculate the string length according to the encoding type .
coder The values of represent different coding types :
- 0: Said the use of
Latin-1
( Single byte encoding ); - 1: Use
UTF-16
.
String The immutability of
I understand String
After the basic composition of , Find out String There is also a sexier feature than the outside , She was final
Keyword modification ,char An array is .
We know that the class is final The modifier represents that the class is not inheritable , and char[]
By final+private
modification , On behalf of String
The object cannot be changed .
String Once the object is created successfully , It can't be changed any more .
final Benefits of modification
Security
When you call other methods , For example, before calling some system level operation instructions , There may be a series of checks .
If it's a mutable class , Maybe after you check , Its internal value has been changed , This may cause serious system crash .
High performance cache
String
Immutability can guarantee hash
It's worth being unique , To make similar HashMap
The container can realize the corresponding key-value
Caching function .
Implement string constant pool
Due to immutability , To implement the string constant pool .
String constant pool refers to when creating strings , Go first 「 Constant pool 」 Find out if the has been created 「 character string 」;
If there is , Will not open up a new space to create a string , Instead, the reference to the string in the constant pool is directly returned to this object .
There are two ways to create strings :
- String str1 = “ Code byte ”;
- String str2 = new String(“ Code byte ”);
When you create a string object using the first method in your code ,JVM First, it checks whether the object is in the string constant pool , If in , Return the object reference .
Otherwise the new string will be created in the constant pool , And return the reference .
This can Reduce duplicate creation of string objects of the same value , To save memory .
The second way to create , When compiling class files ," Code byte " The string will be put into the constant structure , When the class loads ,“ Code byte " Will be created in the constant pool ;
Calling new when ,JVM The command will call String Constructor for , Create a... In heap memory String object , At the same time, the object points to 「 Constant pool 」 Medium “ Code byte ” character string ,str Point to the... Just created on the heap String object ;
Here's the picture :
What are objects and object references ?
str Literal belonging to the method stack , It points to... In the heap String object , Not the object .
Object is a memory address in memory ,str Is a reference to this memory address .
in other words str It's not an object , It's just an object reference .
Margo , What exactly does immutability of string mean ?
String str = "Java";str = "Java,yyds"
First assignment 「Java」, The second assignment 「Java,yyds」,str The value does change , Why do I still say String The object is immutable ?
This is because str It's just String References to objects , It's not the object itself .
The real object is still in memory , Not changed .
Optimize the actual battle
I understand String Object implementation principle and characteristics , It's time to go deep into the goddess's heart , Combined with the actual scene , How to optimize to a higher level String Use of objects .
How to build large strings
since String The object is immutable , So do we mean to create multiple objects when we splice strings frequently ?
String str = " The toad teases the Frog " + " Ugly " + " Play with flowers ";
Do you think Mr. Cheng 「 The toad teases the Frog 」 object , generating 「 The toad teases the frog. It looks ugly 」 object , The last generation 「 The toad teased the ugly flower of the Frog 」 object .
In operation , Only one object generates .
Why is that ?
Although the code is ugly , But the compiler automatically optimizes the code .
Let's look at the following example :
String str = " Little frog ";for(int i=0; i<1000; i++) { str += i;}
After the above code is compiled , You can see that the compiler also optimizes this code .
Java In string splicing , Prefer to use StringBuilder, This can improve the efficiency of the program .
String str = " Little frog ";for(int i=0; i<1000; i++) { str = (new StringBuilder(String.valueOf(str))).append(i).toString();}
Even so , Or create repeatedly in a loop StringBuilder
object .
On the blackboard
So when doing string splicing , I suggest that you still use String Builder To improve system performance .
If in multithreaded programming ,String Object splicing involves thread safety , You can use StringBuffer.
Application intern Save memory
Look directly at intern()
Method definition and source code :
intern()
It's a local approach , It's defined as , When calling intern
When the method is used , If the string constant pool already contains this string , Then directly return the reference of this string .
Otherwise, add this string to the constant pool , And return a reference to the string .
If this string is not included , First add the string to the constant pool , Return the reference of this object .
When is it suitable to use
intern()
Method ?
Twitter An engineer once shared a String.intern()
Use example of ,Twitter Every time the status of a message is released , Will generate an address message , At that time Twitter Size of users , Server needs 20G To store address information .
public class Location { private String city; private String region; private String countryCode; private double longitude; private double latitude;}
Considering that many users have coincidence Of , such as , Country 、 Province 、 Cities, etc , In this case, you can list this information in a separate class , To reduce repetition , The code is as follows :
public class SharedLocation { private String city; private String region; private String countryCode;}public class Location { private SharedLocation sharedLocation; double longitude; double latitude;}
By optimizing the , The data storage size has been reduced to 20G about .
But for memory to store this data , Still great , What shall I do? ?
Twitter Used by the Engineer String.intern()
Make the highly repetitive address information storage size from 20G Down to a few hundred trillion , So it optimizes String Object storage .
The core code is as follows :
SharedLocation sharedLocation = new SharedLocation();sharedLocation.setCity(messageInfo.getCity().intern());sharedLocation.setCountryCode(messageInfo.getRegion().intern());sharedLocation.setRegion(messageInfo.getCountryCode().intern());
Get a simple example to understand :
String a =new String("abc").intern();String b = new String("abc").intern();System.out.print(a==b);
Output results :true
.
When the class is loaded, a string object will be created in the constant pool , The content is 「abc」.
Create local a variable , call new Sting() Will create a... In heap memory String object ,String Object char Array will refer to string in constant pool .
Calling intern After method , Will go to the constant pool to find whether there is a reference equal to the string object , If there is one, return the reference .
establish b variable , call new Sting() Will create a... In heap memory String object ,String Object char Array will refer to string in constant pool .
Calling intern After method , Will go to the constant pool to find whether there is a reference equal to the string object , If yes, it returns a reference to a local variable .
And the two objects just in heap memory , Because there is no reference to it , Will be recycled .
therefore a and b It refers to the same object .
String segmentation has a clever trick
Split() Method uses regular expression to realize its powerful segmentation function , The performance of regular expressions is very unstable .
Improper use can cause backtracking problems , Likely to lead to CPU stay in a high position without going down .
Java The engine implementation used for regular expressions is NFA(Non deterministic Finite Automaton, The deterministic type has finite automata ) automata , This regular expression engine can backtrace when matching characters (backtracking), And once backtracking happens , Then it will take a long time , It could be a few minutes , It could be hours , The length of time depends on the number and complexity of backtracking .
So we should use Split()
Method , We can use String.indexOf()
Methods to replace Split()
Method to complete the string segmentation .
Summary and reflection
We from String Evolution has mastered her composition , Constantly changing member variables saves memory .
Her immutability enables the string constant pool , Reduce duplicate creation of the same string , To save memory .
But also because of this characteristic , When we do long string splicing , Need to show use StringBuilder, To improve string splicing performance .
Last , In terms of optimization , We can also use intern Method , Let the variable string object reuse the same value object in the constant pool , And save memory .
Last , Give us a question , Feel free to leave a comment in the comments section , If you like many books, you will get the books presented by brother code .
Three objects are created in three different ways , Then match in pairs , Whether the two objects matched in each group are equal ? The code is as follows :
String str1 = "abc";String str2 = new String("abc");String str3 = str2.intern();assertSame(str1 == str2);assertSame(str2 == str3);assertSame(str1 == str3)
Male zhong Back office reply No :「String」 Get answers .
边栏推荐
- Is it safe to open a new bond account
- 打新债网上开户安全吗,需要注意什么
- PAT B1081
- Randomly generate 100 non repeating numbers between 1 and 150 and put them in the array
- PAT B1091
- The functions in the applet page are better than those in app JS first execution solution
- PAT B1086
- Electronic package to generate EXE file
- PAT B1057
- Is it safe to open an online account for new bonds? What should be paid attention to
猜你喜欢
Record Baidu search optimization thinking analysis
Can GoogleSEO only do content without external chain? (e6zzseo)
Vulnhub range - correlation:2
Bloom filter
rmi-registry-bind-deserialization
Vulnhub range - the planes:venus
Miner's Diary: why should I go mining on April 5, 2021
200 OK (from memory cache) and 200 OK (from disk cache)
Arduino ide + esp8266+mqtt subscribe to publish temperature and humidity information
PHP Chinese regular
随机推荐
Is it safe to open a new bond account
Arduino ide + esp8266+mqtt subscribe to publish temperature and humidity information
Vulnhub range - correlation:2
Jsonp processing non homologous
Determine whether it is a web page opened on wechat
<C>. array
2.4 finding the sum of the first n terms of the interleaved sequence
Vscode debugging PHP configuration Xdebug
在打新债开户证券安全吗
Is it safe to open an online account for new bonds? What should be paid attention to
Vulnhub range - darkhole 1
Is it safe to open a new bond? Is low commission reliable
PHP synchronizes website content to hundreds of websites to improve SEO ranking
Analyse du code source du processus d'acquisition et de connexion hikaricp II
Wechat applet swiper simple local picture display appears large blank
Uniapp waterfall flow, applet waterfall flow, very simple, suitable for the whole platform
Mysql database design suggestions
Randomly generate 100 non repeating numbers between 1 and 150 and put them in the array
Read multiple associations from a field using delimiters in laravel
打新债证券开户安全吗