Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use SparseArrayCompat for better performance #108

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions Kotlin/lib/src/main/java/com/wolt/blurhashkt/BlurHashDecoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.wolt.blurhashkt

import android.graphics.Bitmap
import android.graphics.Color
import androidx.collection.SparseArrayCompat
import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.withSign
Expand All @@ -11,8 +12,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 @@ -133,21 +134,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