ソースを参照

Refactors Data.checksum() increasing performance 5 times.

Tests on MacBook Pro 2018 (2,3 GHz Quad-Core Intel Core i5, RAM LPDDR3) show for data of random 1_000_000 bytes:
* original implementation 0.586 sec
* proposed implementation 0.126 sec
* also tried `UInt16(bytes.lazy.map(UInt32.init).reduce(UInt32(0),+) % 65535)` which takes 0.417 sec
Valeriy Van 5 年 前
コミット
5195074749
1 ファイル変更3 行追加6 行削除
  1. 3 6
      Sources/CryptoSwift/Foundation/Data+Extension.swift

+ 3 - 6
Sources/CryptoSwift/Foundation/Data+Extension.swift

@@ -18,13 +18,10 @@ import Foundation
 extension Data {
 extension Data {
   /// Two octet checksum as defined in RFC-4880. Sum of all octets, mod 65536
   /// Two octet checksum as defined in RFC-4880. Sum of all octets, mod 65536
   public func checksum() -> UInt16 {
   public func checksum() -> UInt16 {
-    var s: UInt32 = 0
-    let bytesArray = bytes
-    for i in 0 ..< bytesArray.count {
-      s = s + UInt32(bytesArray[i])
+    let s = self.withUnsafeBytes { buf in
+        return buf.lazy.map(UInt32.init).reduce(UInt32(0), +)
     }
     }
-    s = s % 65536
-    return UInt16(s)
+    return UInt16(s % 65535)
   }
   }
 
 
   public func md5() -> Data {
   public func md5() -> Data {