ios - 斯威夫特基金会.数据。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!)
结果:
- 就在容量为 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
- 追加数据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
- 再追加一次 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
- 删除所有保持容量为真
buffer Data 0 bytes _representation Data._Representation empty
什么?!为什么?!容量被重置!
- 再次追加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
- 再次追加 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 为假,但我明确地将其设置为真。可能是我做错了什么......使用容量我试图在附加新部分时避免数据处理。
解决方案
推荐阅读
- matlab - 如何将输入信号导入 simulink 项目?
- ruby - 在页面中拦截 HTTP 请求
- visual-c++ - 尝试在调试模式下运行 UnitTest 并在 CppUnitTest.h 文件中引发异常?
- list - 如何使用地图
使用 DropDownMenu 小部件颤振 - javascript - 家长仅在具有学生级帐户的 Chromebook 上不会收到来自 iframe 的 postMessage
- javascript - Blazor Wasm 中不同屏幕尺寸的事件处理
- google-apps-script - 将 Google Sheet 导出为 .xlsx 并将文件发送到服务器
- dataset - 是否有基于 OCR 的字符距离的公开数据?
- verilog - Verilog 顺序乘法器
- react-native - @react-native-picker/picker 不显示选择的标签