将字节转换为包含 Scala 中每个单独位的布尔数组的最快方法是什么?
What is the fastest way to convert bytes to a boolean array containing each seperate bit in Scala?
在 Scala 中实现霍夫曼算法并将结果写入文件后,我现在正在构建解码器。为此,我需要将从文件中读取的 List[Char]
转换为包含每个单独位的 List[Boolean]
。由于它是一个大文件,我需要以最快的方式执行此操作。
我目前有以下算法:
def uncompress(fileString : String, fileChars : List[Char]) : String = {
var bools:List[Boolean] = List[Boolean]()
fileChars.foreach(f => bools = bools ++ byte2Bools(f))
}
def byte2Bools(b: Char): Seq[Boolean] =
0 to 7 map isBitSet(b)
def isBitSet(byte: Char)(bit: Int): Boolean =
((byte >> bit) & 1) == 1
然而,在一个600KB的文件上完成这个算法需要30多分钟!另外,我不确定我在创建这个算法时是否犯了一些错误。
如何改进它以获得更好的性能?
fileChars.flatMap(byte2Bools)
会更快地将 List[Char]
转换为 List[Boolean]
。
但是将 List
与基本类型一起使用已经意味着您有大量的内存开销,对于 Boolean
更是如此。我会使用 String
作为字符,使用 Array[Boolean]
或 BitSet
作为位(因为你提前知道长度)开始。当然,这会使代码更复杂...
在 Scala 中实现霍夫曼算法并将结果写入文件后,我现在正在构建解码器。为此,我需要将从文件中读取的 List[Char]
转换为包含每个单独位的 List[Boolean]
。由于它是一个大文件,我需要以最快的方式执行此操作。
我目前有以下算法:
def uncompress(fileString : String, fileChars : List[Char]) : String = {
var bools:List[Boolean] = List[Boolean]()
fileChars.foreach(f => bools = bools ++ byte2Bools(f))
}
def byte2Bools(b: Char): Seq[Boolean] =
0 to 7 map isBitSet(b)
def isBitSet(byte: Char)(bit: Int): Boolean =
((byte >> bit) & 1) == 1
然而,在一个600KB的文件上完成这个算法需要30多分钟!另外,我不确定我在创建这个算法时是否犯了一些错误。
如何改进它以获得更好的性能?
fileChars.flatMap(byte2Bools)
会更快地将 List[Char]
转换为 List[Boolean]
。
但是将 List
与基本类型一起使用已经意味着您有大量的内存开销,对于 Boolean
更是如此。我会使用 String
作为字符,使用 Array[Boolean]
或 BitSet
作为位(因为你提前知道长度)开始。当然,这会使代码更复杂...