使用Kotlin Pair实现Android ViewPagerAdapter的性能疑问
Pair in ViewPagerAdapter Great question! Let's break down how using a single ArrayList<Pair<Fragment, String>> compares to two separate lists in terms of performance, along with practical context for ViewPager use cases.
Memory Overhead
First, let's talk about memory usage:
- Original implementation: You maintain two
ArrayListinstances, each carrying its own internal metadata (size, capacity, backing array) plus references to eitherFragmentorStringobjects. - Pair-based implementation: You have one
ArrayListholdingPairobjects. EachPairis a lightweight Kotlin data class that wraps two references (theFragmentand its title).
The only minor difference here is that each Pair adds a tiny bit of overhead from the object header (a few bytes per instance). However, this is completely negligible for ViewPager scenarios—since ViewPagers rarely hold more than 5-10 fragments at a time, the total extra memory is measured in bytes, not megabytes. For extremely large datasets this might add up, but that's not a typical use case for ViewPager.
Access Speed
When accessing elements (like in getItem or getPageTitle):
- In the original code, you directly fetch an element from the list:
mFragmentList[position]. - In the Pair version, you first get the
Pairfrom the list, then access itsfirstorsecondproperty:pairs[position].first.
Don't fret about this extra step! Kotlin's Pair uses simple val properties, which the JVM optimizes to direct field access (no hidden method calls or overhead). In practice, the JIT compiler will likely inline these accesses, making performance identical to the original implementation.
Garbage Collection Impact
Both implementations have nearly identical GC behavior:
- In the original code, when fragments are destroyed, their references in the fragment list become eligible for GC (assuming no other references exist).
- In the Pair version, the
Pairobject will also become eligible for GC once the fragment and title are no longer referenced. SincePairis immutable and holds no extra state, it doesn't add meaningful GC pressure compared to the two-list approach.
Practical Takeaway
For ViewPager adapters (which almost always have small numbers of fragments), the performance difference between the two approaches is indistinguishable to end users. The Pair-based implementation offers clear, tangible benefits:
- Fewer lines of code, making it easier to read and maintain.
- Eliminates the risk of bugs where you forget to add a title to the title list when adding a fragment.
So go ahead and use the Pair-based version—your code will be cleaner without any meaningful performance tradeoff.
内容的提问来源于stack exchange,提问作者Sagar Chapagain

