How to reduce the number of objects created in Scala?

后端 未结 5 1654
余生分开走
余生分开走 2021-02-08 03:24

I\'m programming a computer graphics application in Scala which uses a RGB class to return the color at a point in the image. As you can imagine, the function which return the c

5条回答
  •  渐次进展
    2021-02-08 04:02

    In terms of memory friendliness, the most efficient solution is to store the complete color information just in one Int. As you have mentioned correctly, the color information requires just three bytes, so the four bytes of Int are enough. You could encode and decode the RGB information from one Int by using bit operations:

    def toColorCode(r: Int, g: Int, b: Int) = r << 16 | g << 8 | b
    
    def toRGB(code: Int): (Int, Int, Int) = (
      (code & 0xFF0000) >> 16, 
      (code & 0x00FF00) >> 8, 
      (code & 0x0000FF)
    )
    

提交回复
热议问题