首页 > 解决方案 > 斯威夫特基金会.数据。keepCapacity 标志是否有效?

问题描述

我不是 Swift 专家,在 Foundation.Data 实例上尝试使用 removeAll(keepingCapacity: true) API 时遇到奇怪的行为

https://developer.apple.com/documentation/foundation/data/2224169-removeall

keepCapacity 传递 true 以请求集合避免释放其存储。当您计划再次增加集合时,保留集合的存储可能是一个有用的优化。默认值为假。

斯威夫特版本:5

好的!

我做了以下实验:

var buffer = Data(capacity: 1800)

// data2 is some another Data to append
buffer.append(data2!)
buffer.append(data2!)
            
buffer.removeAll(keepingCapacity: true)

buffer.append(data2!)
buffer.append(data2!)

结果:

  1. 就在容量为 1800 的创建之后:
buffer    Data    0 bytes
_representation   Data._Representation    slice
slice Data.InlineSlice
slice Range<Data.HalfInt> 0..<0
storage   __DataStorage   0x40000002831e0500
_bytes    UnsafeMutableRawPointer?    0x12200ce00 0x000000012200ce00
_length   Int 0
_capacity Int 1800
_offset   Int 0
_deallocator  ((UnsafeMutableRawPointer, Int) -> Void)?   nil none
_needToZero   Bool    true
  1. 追加数据2
buffer    Data    32 bytes    
_representation   Data._Representation    slice
slice Data.InlineSlice    
slice Range<Data.HalfInt> 0..<32  
storage   __DataStorage   0x40000002831e0500
_bytes    UnsafeMutableRawPointer?    0x12200ce00 0x000000012200ce00
_length   Int 32
_capacity Int 1800
_offset   Int 0
_deallocator  ((UnsafeMutableRawPointer, Int) -> Void)?   nil none
_needToZero   Bool    true
  1. 再追加一次 data2
buffer    Data    64 bytes    
_representation   Data._Representation    slice
slice Data.InlineSlice    
slice Range<Data.HalfInt> 0..<64
storage   __DataStorage   0x40000002831e0500
_bytes    UnsafeMutableRawPointer?    0x12200ce00 0x000000012200ce00
_length   Int 64
_capacity Int 1800
_offset   Int 0
_deallocator  ((UnsafeMutableRawPointer, Int) -> Void)?   nil none
_needToZero   Bool    true
  1. 删除所有保持容量为真
buffer    Data    0 bytes 
_representation   Data._Representation    empty

什么?!为什么?!容量被重置!

  1. 再次追加data2

已经没有初始容量了!

buffer    Data    32 bytes    
_representation   Data._Representation    slice
slice Data.InlineSlice    
slice Range<Data.HalfInt> 0..<32  
storage   __DataStorage   0x40000002831e0500
_bytes    UnsafeMutableRawPointer?    0x2812e1f00 0x00000002812e1f00
_length   Int 32
_capacity Int 32
_offset   Int 0
_deallocator  ((UnsafeMutableRawPointer, Int) -> Void)?   nil none
_needToZero   Bool    true
  1. 再次追加 data2 一次
buffer    Data    64 bytes    
_representation   Data._Representation    slice
slice Data.InlineSlice    
slice Range<Data.HalfInt> 0..<64  
storage   __DataStorage   0x40000002831e0500
_bytes    UnsafeMutableRawPointer?    0x2836cc780 0x00000002836cc780
_length   Int 64
_capacity Int 96
_offset   Int 0
_deallocator  ((UnsafeMutableRawPointer, Int) -> Void)?   nil none
_needToZero   Bool    true

有人可以解释这种行为吗?它的工作方式好像 keepCapacity 为假,但我明确地将其设置为真。可能是我做错了什么......使用容量我试图在附加新部分时避免数据处理。

标签: iosswift

解决方案


推荐阅读