Duff的设备在Swift中
我们知道
Duff’s device使用隔行开关和循环的结构交错,如:
send(to,from,count) register short *to,*from; register count; { register n = (count + 7) / 8; switch (count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while (--n > 0); } } 现在,在Swif 2.1中,switch-case control flows并没有像我们在Swift文档中读到的那样隐含起来:
现在,鉴于在Swift中明确存在一个突破性副作用,有一个通过条款:
这非常像: let integerToDescribe = 5 var description = "The number (integerToDescribe) is" switch integerToDescribe { case 2,3,5,7,11,13,17,19: description += " a prime number,and also" fallthrough default: description += " an integer." } print(description) // prints "The number 5 is a prime number,and also an integer." 考虑到维基百科提醒我们,这些设备来自这个问题 A straightforward code to copy items from an array to a memory-mapped output register might look like this: do { /* count > 0 assumed */ *to = *from++; /* "to" pointer is NOT incremented,see explanation below */ } while(--count > 0); 哪个是Swift中Duff设备的确切实现? 这只是一种语言和编码问题,它不适用于真正的Swift应用程序.
您可以在最高级别的代码中表达您的意图,并信任Swift编译器为您优化它,而不是尝试自己优化它. Swift是一种高级语言.您不需要使用高级语言进行低级循环展开.
特别是在Swift中,您不必担心复制数组(Duff设备的原始应用程序),因为Swift假装在分配数组时使用“copy on write”复制数组.这意味着只要您只是从它们中读取它就会对两个变量使用相同的数组,但只要您修改其中一个变量,它就会在后台创建一个副本. 例如,从https://developer.apple.com/documentation/swift/array开始 Each array has an independent value that includes the values of all of its elements. For simple types such as integers and other structures,this means that when you change a value in one array,the value of that element does not change in any copies of the array. For example: var numbers = [1,2,4,5] var numbersCopy = numbers numbers[0] = 100 print(numbers) // Prints "[100,5]" print(numbersCopy) // Prints "[1,5]" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |