0

I have like below code,

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val view = holder.view
    view.apply {
        name.text = list[position].name
        age.text = list[position].age
        address1.text = list[position].address1
        address2.text = list[position].address2
        zip_code.text = list[position].zip_code
    }
}

it's seeking the data multiple times to get each property, like name, age, address1..

And I'm wondered is it better assign the data to a variable and use it? like this,

val view = holder.view
val data = list[position]
view.apply {
    name.text = data.name
    age.text = data.age
    address1.text = data.address1
    address2.text = data.address2
    zip_code.text = data.zip_code
}

Assigning to new variable is cost more?

Please advise me which is better and why?

Expert wanna be
  • 10,218
  • 26
  • 105
  • 158
  • that depends on `list` implementation. in case of `arraylist` get(index) complexity is O(1) so both will have same performance. – Saurabh Nov 16 '17 at 07:36
  • If it is same complexity then the first one is better? because it saves the single variable – Expert wanna be Nov 16 '17 at 07:40
  • Even at `O(1)` complexity, accessing the element multiple times will have worse performance - unless the compiler or proguard or the runtime can optimize it to just one access. – zsmb13 Nov 16 '17 at 08:10

2 Answers2

2

The second is probably better due to 2 reasons:

  1. You don't have to access the list at a specified index multiple times, but only once (access costs depending on the actual implementation)

  2. it's much more readable and also less error-prone to reduce these duplicates

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
0
val view = holder.view
view.apply { list[position].also { data ->
    name.text = data.name
    age.text = data.age
    address1.text = data.address1
    address2.text = data.address2
    zip_code.text = data.zip_code
}}
user8320224
  • 198
  • 4