Skip to content

Commit

Permalink
Android: Use SparseArrayCompat for better performance and lower memor…
Browse files Browse the repository at this point in the history
…y usage

Before: 64,136 bytes
After: 8,072 bytes

See woltapp/blurhash#108
  • Loading branch information
mrousavy committed Feb 19, 2021
1 parent 51437e3 commit 5b279e6
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions android/src/main/java/com/mrousavy/blurhash/BlurhashDecoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.mrousavy.blurhash

import android.graphics.Bitmap
import android.graphics.Color
import androidx.collection.SparseArrayCompat
import com.mrousavy.blurhash.Utils.linearToSrgb
import com.mrousavy.blurhash.Utils.signedPow2
import com.mrousavy.blurhash.Utils.srgbToLinear
Expand All @@ -14,8 +15,8 @@ object BlurHashDecoder {
// cache Math.cos() calculations to improve performance.
// The number of calculations can be huge for many bitmaps: width * height * numCompX * numCompY * 2 * nBitmaps
// the cache is enabled by default, it is recommended to disable it only when just a few images are displayed
private val cacheCosinesX = HashMap<Int, DoubleArray>()
private val cacheCosinesY = HashMap<Int, DoubleArray>()
private val cacheCosinesX = SparseArrayCompat<DoubleArray>()
private val cacheCosinesY = SparseArrayCompat<DoubleArray>()

/**
* Clear calculations stored in memory cache.
Expand Down Expand Up @@ -114,21 +115,21 @@ object BlurHashDecoder {
private fun getArrayForCosinesY(calculate: Boolean, height: Int, numCompY: Int) = when {
calculate -> {
DoubleArray(height * numCompY).also {
cacheCosinesY[height * numCompY] = it
cacheCosinesY.put(height * numCompY, it)
}
}
else -> {
cacheCosinesY[height * numCompY]!!
cacheCosinesY.get(height * numCompY)!!
}
}

private fun getArrayForCosinesX(calculate: Boolean, width: Int, numCompX: Int) = when {
calculate -> {
DoubleArray(width * numCompX).also {
cacheCosinesX[width * numCompX] = it
cacheCosinesX.put(width * numCompX, it)
}
}
else -> cacheCosinesX[width * numCompX]!!
else -> cacheCosinesX.get(width * numCompX)!!
}

private fun DoubleArray.getCos(
Expand Down

0 comments on commit 5b279e6

Please sign in to comment.