From 5f7141fd78b418f6e2ce526d2d5dea0809198f25 Mon Sep 17 00:00:00 2001 From: Timofey Solomko Date: Sat, 22 May 2021 23:34:31 +0300 Subject: [PATCH] Replace Int arrays in EncodingTree with a new CodingIndex struct The hope is that this will improve memory layout/management, and, consequently, improve performance (slightly). --- Sources/Common/CodingTree/EncodingTree.swift | 21 +++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/Sources/Common/CodingTree/EncodingTree.swift b/Sources/Common/CodingTree/EncodingTree.swift index a0fc7f8f..5fe0a7bb 100644 --- a/Sources/Common/CodingTree/EncodingTree.swift +++ b/Sources/Common/CodingTree/EncodingTree.swift @@ -6,22 +6,29 @@ import Foundation import BitByteData +fileprivate struct CodingIndex { + + let treeCode: Int + let bitSize: Int + +} + final class EncodingTree { private let bitWriter: BitWriter - private let codingIndices: [[Int]] + private let codingIndices: [CodingIndex] init(codes: [Code], _ bitWriter: BitWriter, reverseCodes: Bool = false) { self.bitWriter = bitWriter - var codingIndices = Array(repeating: [-1, -1], count: codes.count) + var codingIndices = Array(repeating: CodingIndex(treeCode: -1, bitSize: -1), count: codes.count) for code in codes { // Codes have already been reversed. // TODO: This assumption may be only correct for Huffman codes. let treeCode = reverseCodes ? code.code : code.code.reversed(bits: code.bits) - codingIndices[code.symbol] = [treeCode, code.bits] + codingIndices[code.symbol] = CodingIndex(treeCode: treeCode, bitSize: code.bits) } self.codingIndices = codingIndices @@ -33,10 +40,10 @@ final class EncodingTree { let codingIndex = self.codingIndices[symbol] - guard codingIndex[0] > -1 + guard codingIndex.treeCode > -1 else { fatalError("Symbol is not found.") } - self.bitWriter.write(number: codingIndex[0], bitsCount: codingIndex[1]) + self.bitWriter.write(number: codingIndex.treeCode, bitsCount: codingIndex.bitSize) } func bitSize(for stats: [Int]) -> Int { @@ -45,10 +52,10 @@ final class EncodingTree { guard symbol < self.codingIndices.count else { fatalError("Symbol is not found.") } let codingIndex = self.codingIndices[symbol] - guard codingIndex[0] > -1 + guard codingIndex.treeCode > -1 else { fatalError("Symbol is not found.") } - totalSize += count * codingIndex[1] + totalSize += count * codingIndex.bitSize } return totalSize }