在比较迅速阵列 [英] Compare arrays in swift

查看:108
本文介绍了在比较迅速阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解如何迅速比较数组。

Trying to understand how swift compares arrays.

var myArray1 : [String] = ["1","2","3","4","5"]
var myArray2 : [String] = ["1","2","3","4","5"]

// 1) Comparing 2 simple arrays

if(myArray1 == myArray2) {
    println("Equality")
} else {
    println("Equality no")
}
// -> prints equality -> thanks god

// 2) comparing to a "copy" of an array

// swift copies arrays when passed as parameters (as per doc)
func arrayTest(anArray: [String]) -> Bool {
    return anArray == myArray1
}

println("Array test 1 is \(arrayTest(myArray1))")
println("Array test 2 is \(arrayTest(myArray2))")
// equality works for both

myArray2.append("test")
println("Array test 2 is \(arrayTest(myArray2))")
// false (obviously)

myArray2.removeAtIndex(5)
println("Array test 2 is \(arrayTest(myArray2))")
// true

苹果说,有上阵副本幕后的优化。貌似有时候 - 并非总是 - 结构实际上复制或不能

Apple says there are optimisations behind the scene on array copies. Looks like sometimes - not always - structures are actually copied or not.

这表示,

1)是==遍历所有数组执行基于元件对比? (貌似)
- >如何性能/内存使用量非常大的数组然后

1) is == iterating over all the array to perform a element-based comparison ? (looks like it) -> How about performance / memory usage on very large arrays then ?

2),我们肯定==永远不会返回true,如果所有元素都是平等的吗?我对Java字符串==的不好的回忆

2) Are we sure == will ever return true if all elements are equal ? I have bad memories of == on Java Strings

3)有没有一种方法,以检查是否myArray1和myArray2在技术上使用同一个记忆区/指针/等?了解如何优化工程和潜在的警告后,我来的。

3) Is there a way to check if myArray1 and myArray2 are technically using the same "memory location" / pointer / etc. ? i'm after understanding how the optimisation works and potential caveats.

感谢。

推荐答案

您说的没错稍微紧张 ==

struct NeverEqual: Equatable { }
func ==(lhs: NeverEqual, rhs: NeverEqual)->Bool { return false }
let x = [NeverEqual()]
var y = x
x == y  // this returns true

[NeverEqual()] == [NeverEqual()] // false
x == [NeverEqual()] // false

let z = [NeverEqual()]
x == z // false

x == y // true

y[0] = NeverEqual()
x == y // now false

为什么呢?斯威夫特阵列不符合 Equatable ,但他们有一个 == 运营商,标准库的定义:

Why? Swift arrays do not conform to Equatable, but they do have an == operator, defined in the standard library as:

func ==<T : Equatable>(lhs: [T], rhs: [T]) -> Bool

该运营商将遍历在 LHS 元素和 RHS ,在每个位置比较值。它的的做一个比较按位 - 它调用每对元素的== 运营商。这意味着如果你编写自定义的 == 为您的元素,它会被调用。

This operator loops over the elements in lhs and rhs, comparing the values at each position. It does not do a bitwise compare – it calls the == operator on each pair of elements. That means if you write a custom == for your element, it’ll get called.

但它包含了一个优化 - 如果两个数组基础缓冲区是相同的,它不打扰,它只是返回true(它们包含相同的元件,当然它们相等!)

But it contains an optimization – if the underlying buffers for the two arrays are the same, it doesn’t bother, it just returns true (they contain identical elements, of course they’re equal!).

这问题完全是在 NeverEqual 平等运营商的过错。平等应该是传递的,对称的和反思,而这一次是不是反身( X == X 是假的)。但它仍然会抓住你措手不及。

This issue is entirely the fault of the NeverEqual equality operator. Equality should be transitive, symmetric and reflexive, and this one isn't reflexive (x == x is false). But it could still catch you unawares.

斯威夫特阵列写入时复制 - 所以,当你写 VAR点¯x==是它实际上并没有做数组的副本,它只是指向 X 的存储缓冲区位于 y指示器的。只有当 X 后突变它然后进行缓冲的副本,从而使不变变量不受影响。这是至关重要的数组的行为类似于值类型,但仍然是高性能的。

Swift arrays are copy-on-write – so when you write var x == y it doesn’t actually make a copy of the array, it just points x’s storage buffer pointer at y’s. Only if x or y are mutated later does it then make a copy of the buffer, so that the unchanged variable is unaffected. This is critical for arrays to behave like value types but still be performant.

在雨燕的早期版本中,你实​​际上可以称之为 === 的数组(也早期版本中,变异的行为是有点不同,如果你突变 X 也将甚至改变尽管它已被宣布与 - 这吓坏了的人,使他们改变了它)

In early versions of Swift, you actually could call === on arrays (also in early versions, the mutating behaviour was a bit different, if you mutated x, y would also change even though it had been declared with let – which freaked people out so they changed it).

您可以重现还挺 === 与此阵列的旧的行为(非常依赖于实现不被依靠上除了戳和督促调查)技巧

You can kinda reproduce the old behaviour of === on arrays with this (very implementation-dependent not to be relied-on except for poking and prodding investigations) trick:

let a = [1,2,3]
var b = a

a.withUnsafeBufferPointer { outer in 
    b.withUnsafeBufferPointer { inner in 
        println(inner.baseAddress == outer.baseAddress) 
    } 
}

这篇关于在比较迅速阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆