'Impact of converting from string to int in kotlin
Hey I am sorting the list in kotlin. Using sortBy and thenBy. I was wondering is there impact on performance,speed,memory etc. when we converting from string to int when sorting.
Xyz.kt
data class Xyz(
val dataOne: String? = null,
val dataTwo: String? = null,
val dataThree: String? = null
)
Third.kt
fun main() {
val list =getSortedListData()
list.forEach {
println(it)
}
}
private fun getUnSortedDataListData(): List<Xyz> {
return listOf(
Xyz("2", "3", "4"),
Xyz("1", "5", "4"),
Xyz("-1", "6", "4"),
Xyz("-5", "-2", "4"),
Xyz("-10", "-1", "4")
)
}
Is there impact on when we converting from string to int in these function?
private fun getSortedListData(): List<Xyz> {
val getUnSortedDataList = getUnSortedDataListData()
return getUnSortedDataList.sortedWith(
compareBy<Xyz> { // or compareByDescending
it.dataOne?.toInt() ?: 0 // or java.lang.Integer.MAX_VALUE
}.thenBy { // or thenByDescending
it.dataTwo?.toInt() ?: 0 // or java.lang.Integer.MAX_VALUE
}
)
}
Is there any probelem in above code? Can we do better for sorting in above code?
vs
I am thinking before sorting them, I'll convert to int and then sort. Is this better than above approach?
data class Xyz(
val dataOne: String? = null,
val dataTwo: String? = null,
val dataThree: String? = null
) {
val dataOneInInt = dataOne?.toInt()
val dataTwoInInt = dataTwo?.toInt()
}
private fun getSortedListData(): List<Xyz> {
val getUnSortedDataList = getUnSortedDataListData()
return getUnSortedDataList.sortedWith(
compareBy<Xyz> { // or compareByDescending
it.dataOneInInt ?: 0 // or java.lang.Integer.MAX_VALUE
}.thenBy { // or thenByDescending
it.dataTwoInInt ?: 0 // or java.lang.Integer.MAX_VALUE
}
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
