[swift-users] performance question
Rod Brown
rodney.brown6 at icloud.com
Fri Dec 22 06:30:26 CST 2017
Hi Alexandr,
Equating struct creation with “cheap” or “fast" just because they’re structs isn’t a good idea in Swift. In general, struct creation itself is extremely fast by comparison to creating classes, yes, but it would be incorrect to say “all structs are fast, and all classes are slow”. Structs can hold a significant performance implication as well, though they can also be much faster than classes are too. It depends what the struct does under the hood.
Creating an array allocates a reference based buffer as an internal variable. This means, practically, it is just as slow as a class allocation. The important difference, however, is that structs allow us to share references as pointers under the hood just like classes do. And thus, we can make copies all over the place of the array where we don’t mutate, and have practically fixed cost, because there’s only really one reference - the initial buffer. Then once a mutation happens, the first mutation has a cost and then subsequent mutations drop in cost again.
Structs as wrappers of stack-based variables like Ints, Doubles, Booleans, etc are indeed far cheaper than Classes, yes. But just because it’s a struct doesn’t implicitly make it more performant.
In the case of Date(), Date is a struct that contains a single TimeInterval variable. The only expense apart from the very cheap struct creation is getting the actual date double, which is done with CFAbsoluteTimeGetCurrent(). This means the only expense apart from the very cheap struct creation is calling that C function to get the absolute time.
I can’t categorically state the comparison of Date vs NSDate creation. NSDate also uses tagged pointers in 64bit on ARM, for example, which avoids an allocation where possible by storing the date value inside the pointer.
Ultimately, you aren’t going to get a categorical answer about Structs vs Classes. They each have trade offs and optimisations. The best bet: use the right tool for the job, and then work out if what you’re doing has a performance issue and work from there.
- Rod
> On 13 Dec 2017, at 2:16 am, Седых Александр via swift-users <swift-users at swift.org> wrote:
>
> Hello.
>
> For example we have
>
> Class A {}
> Struct B {}
>
> And code 'let b = B()' will do much faster than code 'let a = A()'
> And therefore code 'let d = Date()' is fast, because Date is struct?
> And I can use it in huge cycles fearlessly?
>
>
>
>
> --
> Alexandr Sedykh
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171222/4a67551a/attachment.html>
More information about the swift-users
mailing list