Why is the static keyword used in UITableViewCell identifiers?

前端 未结 3 1488
挽巷
挽巷 2021-02-01 05:31

I\'ve read up on \"static\" on several occasions, including just before posting this question. I\'m still searching for an \"Aha\" though.

In the context of UITableView\

相关标签:
3条回答
  • 2021-02-01 05:47

    My guess is that by declaring the string as static, that every time it gets passed into -dequeueReusableCellWithIdentifier:CellIdentifierforIndexPath: that the same pointer is used each time (as statically declared variables are allocated only once on the heap, very early in a program's execution)

    [NSString -isEqualToString:] is most likely implemented to perform a pointer compare first, followed by a character-wise compare as the fallback, which I supposed could shave off a few cycles on each iteration.

    There's not much to gain from this, as (a) table cell re-population operates on a typically very small set of cells, and is well optimized, and (b) table refresh is bursty -- it happens once and then doesn't happen again until the user scrolls or application logic changes up the content -- if you end up calling -reloadTable 100 times a second, then there's clearly something wrong with your application logic.

    I suspect the static keyword is a vestigial legacy convention -- maybe back in the day, Apple hashed on the pointer, rather than performing a proper string compare.

    0 讨论(0)
  • 2021-02-01 05:49

    So that it will only be constructed once. If it's not static, you'll be making one every time the message is sent (which is a lot)

    0 讨论(0)
  • 2021-02-01 05:49

    There's no real benefit here. It's mostly just a hint to the reader that the same value is used for all cells in this particular bit of code. As the identifier itself is a constant string, it gets compiled into an immutable chunk of memory and referenced as the same pointer every time, e.g. there is no cost involved in constructing the string even if you remove the static keyword.

    0 讨论(0)
提交回复
热议问题