The Eclipse Memory Analyzer (1.12.0)
The Demo address
String redundancy
In some cases, there are a large number of repeating string objects in memory. The following is a simple example
Data1 holds the string constant pool “aaa… Aaa “references; Data2 contains the heap string “BBB… BBB “citation; Data3 contains the string constant pool “CCC… The address of CCC “.
class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding val data1: Array<String? > = arrayOfNulls(1000) val data2: Array<String? > = arrayOfNulls(1000) val data3: Array<String? > = arrayOfNulls(1000) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) } override fun onResume() { super.onResume() binding.button.setOnClickListener { Log.i(TAG, "onResume: Populate the data ") for (I in data1. Indices) {data1 [I] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } for (i in data2.indices) { val str = StringBuilder("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") data2[i] = str.toString() } for (i in data3.indices) { val str = StringBuilder("cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc") data3[i] = Str.tostring ().intern()} log. I (TAG, "onResume: Filled ")}}}Copy the code
- Across the map, Shallow Heap means the memory occupied by the object itself, and Retained Heap means the amount of memory that can be obtained through the Retained Heap release
String.intern
Can significantly reduce string redundant objects
,
Find redundant string objects
- With Eclipse Memory Ananlyer opens the Hprof file that has been converted to a standard format by Hprof-conv.exe
- Perform the following operations on the Overview page
- For objects in Group By Value type java.lang.String, then Finish
- With Objects sorting, you can find the most repeated character Objects
Determines where the string object is used
Methods a
- Merge Shortest Paths to GC Roots > exclude all phantom/weak/soft etc.references
- The GC path
Way 2
- Use List Objects > With Incoming References to determine which objects the current string object is referenced by
- The string object is stored at data2[0].
Use String#intern to reduce memory
Note the frequency used by String#intern, which adds strings to the string constant pool. String#intern see resources for more details.
Refer to the content
- Shallow and retained sizes
- Parse String#intern in depth