How `@inline(__always) static let` will be optimized?

I have a code like this

struct Content {
   @inline(__always) static let items: [String: String] = ...
}

Then I used the items
var myItems: [String: String]? = Content.items

Then I removed the items
myItems = nil

As far I know, since items is an inline property, the compiler will replace the utilization of items with its content, in the places where it is used, isn't it?

The static variables are designed to be kept in the memory for the entire app life cycle, but considering that in this case where Container.items is used as inline property, doesn't make sense to keep it in the memory as a regular static property.

With that being said, the question is, the compiler actually is going to create a static property, or it just puts the inline code, without storing any static value?

Could this approach, be useful, to create a static variable, without keeping it in memory 'forever'?

Thanks in advance.

You declared your constant as times. Are you trying to refer to the same thing here?

1 Like

let implies storage space. You should use var and make it a computed property if you want to be certain the value isn’t stored:

var times: [String: String] { return ... }

So no need to make it inline to avoid storage.

You can still make it inline if you a really need to avoid a function call, but in general I’d suggest letting the optimizer decide what’s best.

1 Like

Yes, I just updated the example :slightly_smiling_face:.

Thanks, actually I did that in my current implementation, but I am curious to know if this use of 'inline' makes sense for certain cases.

Very broadly speaking, anywhere where @inline(__always) is useful represents a deficiency in the optimizer. However, optimal inlining is probably impossible, so there will likely always be such edge cases.

One thing I do in the standard library sometimes is experimentally take out workarounds like @inline(__always) and rebenchmark, to see if the optimizer has improved to the point that it's no longer needed.

It's also worth noting that the tradeoffs it presents are not always obvious. If you speed up a certain code path at the expense of slowing everything else down due to increased pressure on the processor's instruction cache (from inlining generating more code overall), was that worth it? Hard to say. One heuristic I apply is that inlining is primarily worth it if the increased visibility into the code's structure enables other significant optimizations, for example removing reference counting or dynamic dispatch.

4 Likes