arrays, linked lists, and their performance

Source: Internet
Author: User

Poke links to read the final version

Patient: Doctor Doctor, I'm a pain in the egg
Doctor: Then stop popping.

I said on Twitter:

You warned me that reduce the way I used to build arrays was interesting, but there was a risk of halving performance.

A lot of people think this sentence is very strange, which makes me very surprised. Quite a few people recommend reduce changing the version to not copy the array (i don't think that's possible). It is also suggested that you need to + optimize the operator so that it does not copy (I also don't think it's easy, and we'll be aware of that soon).

Others suggest that I do not need to be concerned with these trivial issues unless the documentation is mentioned (and I think this is something to be aware of when writing code – saying "I only notice when the document tells me there is a problem here" as if "I wrote the correct code only if the unit test results were not displayed correctly". )

Some of the other feedback is related to the article I sent before, why do I implement an outdated data structure? We already have an array, what's the point of its existence?

So, you know why I sometimes mention that this is not a blog only about MAC and IOS programming? This is certainly not a blog only about MAC and IOS programming! Don't do it because I accidentally think a linked list with an enumeration type is fun and you put him in your app. Because I might also be interested in the performance issues that you have followed, and you won't. Nevertheless, I think the example of the list is interesting and worthwhile to implement and play with, and it is possible to reduce help improve the performance of the array method. Even in some (rare) scenarios, it is useful for actual coding.

At the same time, I think some of the extra features of Swift include the flexibility to choose between objects and specific methods, as well as "default security." All of these have made it a very good CS teaching language. The future version of the book may use Swift as the implementation language.

So, in general--sometimes you'll find that using reduce to build an array (a dictionary or a collection), for example, the following reduce map implementation:

extension SequenceType {   func mapUsingReduce<T>(transform: Generator.Element->T) -> [T] {        return reduce([]) { $0 + [transform($1)] }    }}

Relative drops, create a mutable array and then use for the loop to do the mapping implementation:

extension SequenceType {   func mapUsingFor<T>(transform: Generator.Element->T) -> [T] {        varresult: [T] = []        forin self { result.append(transform(x)) }        return result    }}

The difference is that + each time the operation copies an array that is constantly changing. The time it takes to copy an array is linear, that is, traversing the entire array, so as the length of the map array grows, the total time spent is increased by two power.

Still, it's normal for people not to re-implement the map function: You see more of the trick: telling you to go heavy or build a dictionary based on word frequency. But the most essential problems still exist.

But what does this have to do with linked lists? Because you can use the code from the last linked list to implement reduce the map version you're using, like this:

extension SequenceType {    func mapToList<T>(transform: Generator.Element->-> List<T> {        return reduce(List()) { $0.cons(transform($1)) }.reverse()    }}

The result is that this version of performance is only half the version of the array (because of reverse this step), so that your teacher will suspect you are cheating on the test results, rather than the results of the experiment:

The reason for this is that the list is contiguous--the old linked list and the new linked list are always connected by nodes. So no copy is needed. But the price is only to increase the length of the list from the head (so it is needed reverse ), and the list must be completely unchanged. So even if the list has only one reference, it needs to be copied before it is modified. This Array is different from the one that Array can detect when its buffers are accessed individually, and then can be modified directly without the need for a copy. There are other costs to using a linked list-the time it takes to count the number of nodes in the list is twice times the number of elements in the array, since the indirect addressing when traversing the list is time consuming.

So + is it possible to solve the problem that the array is fully copied during operation? Before considering this, let's take a look at a copy-on-write array to help. Mike Ash's Cow x blog has implemented a copy-on-write array, so we changed a bit by using classes in the standard library ManagedBuffer to implement a copy-on-write array.

Managedbuffer

ManagedBufferis a class that can be inherited to simplify allocating/freeing memory operations and memory management on the heap. It is generic, with Value Element These two independent placeholders, which store the type of Element block of n elements, which is dynamically allocated when the instance is created. Valueis the type of variable to which additional information is stored-for example, if you want to implement an array, you need to store the number of elements because the elements need to be destroyed before the memory is released. Access to elements is passed withUnsafeMutablePointerToElements , while access to value can be done through a simple, non-secure method, or directly using .value attributes.

The following code implements a minimalist self-destruct array buffer:

class MyArrayBuffer<Element>: ManagedBuffer<Int,Element> {    deinit {        self.withUnsafeMutablePointerToElements { elems->Voidin            elems.destroy(self.value)        }    }}

In this way, the MyArrayBuffer stored element is still generic, but ManagedBuffer Value set to the Int number of buffer elements to hold (one thing to keep in mind is that we allocate more space than the elements in the array to avoid frequent redistribution).

When a buffer is refactored, it is MyArrayBuffer.deinit ManagedBuffer.deinit called before it frees up ManagedBuffer.deinit memory. This MyArrayBuffer will have the opportunity to destroy all of its objects. If it Element is not just a passive structure, destroying objects is necessary-for example, if the array contains other write-time copy types, destroying them will trigger them to release their own memory.

Now we can create an array-type struct, which is stored using a private buffer:

publicstruct MyArray<Element> {    privatevar _buf: MyArrayBuffer<Element>    publicinit() {        _buf = MyArrayBuffer<Element>.create(8in0as! MyArrayBuffer<Element>    }}

We do not directly MyArrayBuffer use init --and use ManagedBuffer the class method. Because this method returns the parent class, we then cast it down to the correct type.

Then we will MyArray become a collection type:

extension MyArray: CollectionType {    publicvarreturn0 }    publicvarreturn _buf.value }    publicsubscript(idx: Int) -> Element {        else { fatalError("Array index out of range") }        return _buf.withUnsafeMutablePointerToElements { $0[idx] }    }}

Next, we need to add two fairly similar methods to the buffer, one for copying memory and the other for resizing the memory. The copy method is called when shared storage is detected, and the sizing method is called when more memory is needed:

Extension Myarraybuffer {func clone () -Myarraybuffer<Element>{return  Self.withunsafemutablepointertoelements {Oldelems -Myarraybuffer<Element> inch            returnMyarraybuffer<Element>.Create Self.Allocatedelementcount) {NewbufinchNewbuf.withunsafemutablepointertoelements {Newelems -Void inchNewelems.Initializefrom (Oldelems, Count: Self.Value)}return  Self.Value} AS!Myarraybuffer<Element>}} Func Resize (newsize:int) -Myarraybuffer<Element>{return  Self.withunsafemutablepointertoelements {Oldelems -Myarraybuffer<Element> inch             LetElementcount=  Self.ValuereturnMyarraybuffer<Element>.Create (newSize) {NewbufinchNewbuf.withunsafemutablepointertoelements {Newelems -Void inchNewelems.Moveinitializefrom (Oldelems, Count:elementcount)} Self.Value= 0                returnElementcount} AS!Myarraybuffer<Element>}    }}

Building and populating buffers at the same time is a bit harsh--first we need to get a non-secure pointer to an existing element, and then call it, the closure of the create method will receive an object that is only partially built (for example, memory is allocated but not initialized), and the object then needs to call newBuf.withUnsafeMutablePointerToElements To copy the memory from the old buffer to the new buffer.

The main difference between the two methods is clone not to change the elements in the old buffer, but simply to load the new copy into the new buffer. It resize moves the element from the old memory to the new memory (through UnsafeMutablePointer the moveInitializeFrom method), and then updates the old buffer, telling it that there is no need to manage any elements-otherwise, it will try to destroy them at the deinit time.

Finally, let's MyArray add one append and the extend method:

extension MyArray {public  mutating func append  (x:element) {if !isuniquely REFERENCEDNONOBJC (&_buf) {_buf = _buf.clone ()} if  _buf.al Locatedelementcount = = Count {_buf = _buf.resize (Count*2 )} _bu F.withunsafemutablepointers {(val, elems)->void in  (Elems + val.memory++) . Initialize (x)}} public  mutating func extend<s:sequencetype where  s.generator.element = = element> (seq:s) {for  x in  seq {self.append (x)}}}  

This is just a sample code. In fact, you might be able to separate the unique judgment code from the sizing code so that you can reuse it in the subscript set and other slightly changed methods, and I'm simply putting them all in the append way. And, if possible, you'll want to append keep enough space for it to expand so that you can prevent the buffer from being double-copied while it is shared and the space is too small. But all these things do not have much effect on our great blueprint.

Okay, now it's the operator. First, the += assignment operator, which is on the left inout , expands to the left using the content on the right:

func +=<Element, S: SequenceType where S.Generator.ElementElement>  (inout lhs: MyArray<Element{    lhs.extend(rhs)}

Finally, the + operator. We can += implement it in terms of the operator. This operator passes two immutable arrays and merges them into a new array. It relies on a write-time copy action to create a mutable copy of the left-hand content, and then uses the content on the right to extend it:

func +<Element, S: SequenceType where S.Generator.ElementElement>  (lhs: MyArray<Element>, rhs: S) -> MyArray<Element{    var result = lhs    result += rhs    return result}

In fact, you can lhs use var identifiers to further shorten the code before the variable:

func +<Element, S: SequenceType where S.Generator.ElementElement>  (var lhs: MyArray<Element>, rhs: S) -> MyArray<Element{    lhs += rhs    return lhs}

I mentioned the second version because someone suggested that a better reduce strategy might be to add identifiers to the additive parameters var . And this is just lhs like what happened: var what you do is just declaring that the arguments passed in are mutable. It's still a copy-it's not a reference to the original value in some way.

Can the + operator be optimized?

Now that we have a prototype of a fully available copy-on-write array, you can append manipulate it, and it implements the + operators. This also means that we can use it to rewrite reduce the version of the map method:

func mapUsingMyReduce<T>(transform: Generator.Element->T) -> MyArray<T> {    return reduce([]) { $0 + [transform($1)] }}func mapUsingMyFor<T>(transform: Generator.Element->T) -> MyArray<T> {    var result = MyArray<T>()    forin self { result.append(transform(x)) }    return result}

If you record performance with a chart, you'll see that the two pieces of code perform exactly the same way you would with an array implementation.

So, now that we have an implementation that is completely under our own control, can we change the + operator and let it not copy? I don't think we did it.

To see a simpler example, we can change the following code:

a = MyArray<Int>()a.extend(0..<3a + [6,7,8]

And then let it not be copied? It's obvious we can't. bmust be a new copy of the array for the purpose of not affecting a . Even if we b a do not make any changes after the creation, the + operator implementation is not able to know these. Perhaps the compiler will know and then optimize according to the situation, but the + method is impossible to know.

It's also not helpful to check for unique references here. astill exists, so lhs it cannot be the only holder of the buffer.

reducemethod is no different, the following is a possible implementation:

extension sequencetype {func myreduce<t> ( Initial:t, combine : (t,generator.element)->t), T {var result  = initial for  x in  s Elf {result  = combine  (result , X)} return  result}}  

Suppose this combine is { $0 + [transform($1)] } , you will find that the + operator also does not know that we have directly assigned the result to the result variable. Check the code we know that it is possible to add the right side to the left side of the content if possible (theoretically, because although the array is passed as an immutable value, because its buffer is a class, it has the semantics of the reference and can be changed). But + it is impossible to know this by the position of the operator alone. It is only clear that the copy of the left content is not the only holder of the buffer. There is another holder: reduce result A copy of the hold--and it is soon to be discarded and replaced with new results, but this is done after the + operation.

There is also a glimmer of hope that if each array is just their shard (but not--but there is ArraySlice something called, it requires additional overhead to record the start and end points of the Shard into the parent array). If they are, perhaps they can be modified to allow one or only one array to append be ignored by other arrays when doing the operation. But this can usually increase the cost of the array, and the whole array is designed to be fast--you certainly don't want to slow them down for this situation.

There may be a very clever way to solve all of these problems, which may require the help of the compiler or may not be required. But that's still not a good idea. +The action semantics is to create a new array. And it's obviously not the right solution to make it implicitly drop modifying an already existing array in a very specific situation. If necessary, you can var encapsulate it in a small virtual method, as if you didn't use it. But it can still make your code more efficient.

arrays, linked lists, and their performance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.