thomasp85 / farver

High Performance Colourspace Manipulation in R
https://farver.data-imaginist.com
Other
128 stars 14 forks source link

WIP: Implement encode_native() without going through the character vector #35

Closed zeehio closed 2 years ago

zeehio commented 2 years ago

Hi,

Thanks for your farver package. It's nice to have efficient color conversion in R.

I am opening this pull request that improves the performance of encode_native() by avoiding creating an intermediate character vector with the colours.

Here I compare the performance on a 10 million length vector (e.g. from a 10k x 1000 matrix):

library(farver)
x <- runif(1E7)
ramp <- scales::colour_ramp(c("red", "blue"))
colours_chr <- ramp(x)
spectrum <- farver::decode_colour(colours_chr)

bench::mark(
  before = {
    # This was how encode_native worked before
    cols <- encode_colour(spectrum, alpha = 0.75)
    farver:::encode_native(cols)
  },
  after = {
    farver::encode_native(spectrum,alpha = 0.75)
  }
)
#> # A tibble: 2 × 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 before         1.2s     1.2s     0.834   114.5MB     0   
#> 2 after        94.1ms   95.5ms    10.5      38.1MB     2.62

Created on 2022-09-12 by the reprex package (v2.0.1)

The advantage on such a large vector is of a factor of 10. On a 1k long vector, my implementation is 5x faster.

I just discovered nativeRaster objects and I find them super useful for plotting large matrices (in a way similar to what image, filled.contour or annot_raster do). I find those functions slower than what they actually need to be, and I am trying to make a ggplot extension able to provide a nice API and an efficient implementation.

This is my first step towards that goal.

I would appreciate a lot your feedback on this contribution.

zeehio commented 2 years ago

Closing this to make easier-to-review pull requests