1

I did some comparison here: https://github.com/itchingpixels/structs-vs-classes and it seems like inserting a struct into an array of structs is 10x slower than inserting a class to an array of classes (with the same data).

Is something wrong with my tests?

What could be the reason of this? or.. is this expected?

1 Answers1

2

Expected. Classes use references (4-8 byte memory addresses); structs are value types so the entire struct must be inlined. Try with a tiny struct versus one that's hundreds of bytes in size. Try inserting at the end of an array versus the beginning.

BaseZen
  • 8,650
  • 3
  • 35
  • 47
  • thanks for the response, I'm wondering why inserting at the end vs. at the beginning should cause any difference? – Mark Aron Szulyovszky Aug 05 '15 at 15:34
  • Can you post your test code and results, to ground the discussion? I'm thinking that inserting at the beginning causes everything to be moved over -- essentially copying the array one element to the right to make room. – BaseZen Aug 05 '15 at 16:21
  • This goes really deep into it and is a heavyweight Q/A, but it's a year-old question so the compiler has advanced quite a bit since then: http://stackoverflow.com/questions/24101718/swift-performance-sorting-arrays – BaseZen Aug 05 '15 at 16:45
  • I've shared the tests/ code here: https://github.com/itchingpixels/structs-vs-classes. I'll do some more tests with smaller structs, too. I was interested in what the speed improvements were if I used structs as my main model objects, and I'm aware of various upsides of doing so - but I didn't know about their potential slowness when it comes to sorting (which is only slightly slower) or inserting at specific indexes (which is a lot-lot slower). Did I miss out on something? – Mark Aron Szulyovszky Aug 08 '15 at 09:18