Assign count variable over calling .count on Array in Swift
NickName:Sethmr Ask DateTime:2016-08-25T01:57:37

Assign count variable over calling .count on Array in Swift

I occasionally come to a place where I will not be changing the contents of an array, but I need to know its count several times over a function. Is it more efficient to assign the .count of the array to a variable and use it multiple times, or does the compiler make the efficiency equivalent?

Copyright Notice:Content Author:「Sethmr」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/39130061/assign-count-variable-over-calling-count-on-array-in-swift

Answers
dfrib 2016-08-24T19:24:47

Let's investigate! Is myArray.count equivalent to accessing a stored property or is it a computed property performing some \"unnecessary\" calculations if called repeatedly for a non-mutated array? (Disregarding compiler cleverness)\n\n\nswift/stdlib/public/core/Arrays.swift.gyb\n\n\n\n/// The number of elements in the array.\npublic var count: Int {\n return _getCount()\n}\n\n// ... what is function _getCount()?\n\ninternal func _getCount() -> Int {\n return _buffer.count\n}\n\n// ... what is property _buffer?\ninternal var _buffer: _Buffer\n\n// ... what is type _Buffer? (Swift)\ninternal typealias _Buffer = _ContiguousArrayBuffer<Element>\n\n// ... what is type _ContiguousArrayBuffer?\n// --> switch source file\n\n\n\n\nswift/stdlib/public/core/ContiguousArrayBuffer.swift\n\n\n\nimport SwiftShims\n\n/// Class used whose sole instance is used as storage for empty\n/// arrays. The instance is defined in the runtime and statically\n/// initialized. See stdlib/runtime/GlobalObjects.cpp for details.\ninternal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {\n\n // ... conformance to _ArrayBufferProtocol\n\n /// The number of elements the buffer stores.\n internal var count: Int {\n get {\n return __bufferPointer.header.count\n }\n // ...\n } \n // ...\n}\n\n// ... what is property __bufferPointer?\nvar __bufferPointer: ManagedBufferPointer<_ArrayBody, Element>\n\n// what is type _ArrayBody?\n// we notice for now that it is used in the following class:\ninternal final class _EmptyArrayStorage\n : _ContiguousArrayStorageBase {\n // ...\n\n var countAndCapacity: _ArrayBody // telling name for a tuple? :)\n}\n\n// --> proceed to core/ArrayBody.swift\n\n\n\n\nswift/stdlib/public/core/ArrayBody.swift\n\n\n\nimport SwiftShims\n\n// ...\n\ninternal struct _ArrayBody {\n var _storage: _SwiftArrayBodyStorage\n\n // ...\n\n /// The number of elements stored in this Array.\n var count: Int {\n get {\n return _assumeNonNegative(_storage.count)\n }\n set(newCount) {\n _storage.count = newCount\n }\n } \n}\n\n// we are near our price! we need to look closer at _SwiftArrayBodyStorage, \n// the type of _storage, so lets look at SwiftShims, GlobalObjects.cpp\n// (as mentioned in source comments above), specifically\n// --> switch source file\n\n\n\n\nswift/stdlib/public/SwiftShims/GlobalObjects.h\n\n\n\nstruct _SwiftArrayBodyStorage {\n __swift_intptr_t count; \n __swift_uintptr_t _capacityAndFlags;\n};\n\n// Yay, we found a stored property!\n\n\n\nSo in the end count is a stored property and is not computed per call, so it should be no reason to explicitly store the arr.count property by yourself.",


Lu_ 2016-08-24T18:06:08

struct _SwiftArrayBodyStorage {\n __swift_intptr_t count;\n __swift_uintptr_t _capacityAndFlags;\n};\n\n\nthis is the struct that Swift implements. According to this count is there all the time knowing how many elements are in buffer. You probably can use that \n\ninfo form: https://ankit.im/swift/2016/01/08/exploring-swift-array-implementation/\n\nedit for more info \n\npublic var count: Int {\n get {\n return __bufferPointer.value.count\n }\n nonmutating set {\n _sanityCheck(newValue >= 0)\n\n _sanityCheck(\n newValue <= capacity,\n \"Can't grow an array buffer past its capacity\")\n\n __bufferPointer._valuePointer.memory.count = newValue\n }\n}\n",


Jack Lawrence 2016-08-24T18:15:51

It doesn't matter; I'd suggest just doing whatever makes your code simpler and easier to understand. In release builds, the optimizer should inline and notice that the value will be the same across calls. Regardless, Array.count is basically equivalent in performance/codegen to accessing a local variable.",


More about “Assign count variable over calling .count on Array in Swift” related questions

Assign count variable over calling .count on Array in Swift

I occasionally come to a place where I will not be changing the contents of an array, but I need to know its count several times over a function. Is it more efficient to assign the .count of the ar...

Show Detail

pyrocms assign count to variable

I would like to check if is last post from loop. I am using pyroCMS. But problem is that if i am using helper:count two times it is not working correctly. How can i assign helper:count to variable ...

Show Detail

Assign word count value to a variable

I have over 100 files. I want to find lines with a certain value, wc those lines and get the Total word count from all the files. I am not sure how to assign a value to the word count. This is what I

Show Detail

how to assign count() to variable

I need to store dates and the count() in a dataframe. I think I have done so in my code, but I am unable to access the count() to assign it to a variable. Ultimately my goal is to group by a number...

Show Detail

Recursively count items in a multidimensional array in generic and idiomatic Swift

I have a multi-dimensional array and I need a count of all of the items within all of the arrays, excluding container arrays themselves from the count. What would be the most generic and idiomatic

Show Detail

array count error swift

I have searched long, but couldn't find a solution for my bug. Swift somehow doesn't count my array (converted from json) correctly. This is the code I use to create the array: let jsonData = NSData(

Show Detail

Swift: optional array count

In Objective-C, if I had the following property: @property (strong, nonatomic) NSArray * myArray; A method to return a number of objects in myArray would look like: - (NSInteger)

Show Detail

Optional in Swift, return count of array

Help me with Optional hell in Swift. How to return count of array for key "R". self.jsonObj can be null func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -&gt; Int { re...

Show Detail

Count elements of nested array swift

Does anyone know here how to count amount of elements in all nested array of custom objects in Swift? I.e. I have [Comments] array which includes [Attachments] array. There may be 100 comments and 5

Show Detail

Assign value received from @escaping to instance variable in another class in swift

I believe that I misunderstood some conception in Swift and can assign received array to my instance variable. Can somebody explain why overall my announcementsList array has 0 elements?

Show Detail