我偶尔会遇到这样的情况,我不会更改数组的内容,但我需要通过一个函数多次知道它的计数。将数组的 .count 赋值给一个变量并多次使用它更高效,还是编译器使效率等效?
最佳答案
让我们调查一下! myArray.count 是否等同于访问存储的属性,或者如果为非变异数组重复调用,它是否是执行一些“不必要”计算的计算属性? (忽略编译器的聪明程度)
/// The number of elements in the array. public var count: Int { return _getCount() } // ... what is function _getCount()? internal func _getCount() -> Int { return _buffer.count } // ... what is property _buffer? internal var _buffer: _Buffer // ... what is type _Buffer? (Swift) internal typealias _Buffer = _ContiguousArrayBuffer<Element> // ... what is type _ContiguousArrayBuffer? // --> switch source file
import SwiftShims /// Class used whose sole instance is used as storage for empty /// arrays. The instance is defined in the runtime and statically /// initialized. See stdlib/runtime/GlobalObjects.cpp for details. internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol { // ... conformance to _ArrayBufferProtocol /// The number of elements the buffer stores. internal var count: Int { get { return __bufferPointer.header.count } // ... } // ... } // ... what is property __bufferPointer? var __bufferPointer: ManagedBufferPointer<_ArrayBody, Element> // what is type _ArrayBody? // we notice for now that it is used in the following class: internal final class _EmptyArrayStorage : _ContiguousArrayStorageBase { // ... var countAndCapacity: _ArrayBody // telling name for a tuple? :) } // --> proceed to core/ArrayBody.swift
import SwiftShims // ... internal struct _ArrayBody { var _storage: _SwiftArrayBodyStorage // ... /// The number of elements stored in this Array. var count: Int { get { return _assumeNonNegative(_storage.count) } set(newCount) { _storage.count = newCount } } } // we are near our price! we need to look closer at _SwiftArrayBodyStorage, // the type of _storage, so lets look at SwiftShims, GlobalObjects.cpp // (as mentioned in source comments above), specifically // --> switch source file
struct _SwiftArrayBodyStorage { __swift_intptr_t count; __swift_uintptr_t _capacityAndFlags; }; // Yay, we found a stored property!
所以最后 count 是一个存储属性,不是每次调用都计算的,所以应该没有理由自己显式存储 arr.count 属性。
关于arrays - 在 Swift 中对 Array 调用 .count 时分配计数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39130061/
我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)
我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击
通过rubykoans.com,我在about_array_assignment.rb中遇到了这两段代码你怎么知道第一个是非并行赋值,第二个是一个变量的并行赋值?在我看来,除了命名差异之外,代码几乎完全相同。4deftest_non_parallel_assignment5names=["John","Smith"]6assert_equal["John","Smith"],names7end45deftest_parallel_assignment_with_one_variable46first_name,=["John","Smith"]47assert_equal'John
我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是
我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
这个问题在这里已经有了答案:Arraysmisbehaving(1个回答)关闭6年前。是否应该这样,即我误解了,还是错误?a=Array.new(3,Array.new(3))a[1].fill('g')=>[["g","g","g"],["g","g","g"],["g","g","g"]]它不应该导致:=>[[nil,nil,nil],["g","g","g"],[nil,nil,nil]]
尝试在我的RoR应用程序中实现计数器缓存列时出现错误Unknownkey(s):counter_cache。我在这个问题中实现了模型关联:Modelassociationquestion这是我的迁移:classAddVideoVotesCountToVideos0Video.reset_column_informationVideo.find(:all).eachdo|p|p.update_attributes:videos_votes_count,p.video_votes.lengthendenddefself.downremove_column:videos,:video_vot
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www