0

I'm writting a series of anonymous functions for an objective-C project (i.e. these functions are not class specific / implementation is hidden) and I came across an interesting issue...

I have a macro function: div(c)((CGFloat)c/255.0f) This usage will almost always be something like div(0.0f), but others may not know that it takes a float so div(0) is possible

and the question I have is this: when variables are explicitly cast and the variable is of the same type as the cast is any performance lost to the cast?

jscs
  • 63,694
  • 13
  • 151
  • 195
Ryan Dignard
  • 639
  • 1
  • 5
  • 16
  • Can you measure the difference? No? Then why do you worry? – Jens Jan 02 '13 at 22:37
  • 1
    Casting from a type to itself is a no-op. When there is a cast in the source, the compiler emits the required code to convert from origin type to target type. In the case of a cast from `T` to `T`, the required code is: zilch. – Daniel Fischer Jan 02 '13 at 22:47
  • Thanks Daniel... I'd say that is the best answer. I was worrying about it since this is in a very low-level often called system; I didn't want to lose any more performance than necessary – Ryan Dignard Jan 03 '13 at 17:22

2 Answers2

1

A cast is a promise, not a data type, not a method, not an extension. You're just making the compiler comfortable about a type. Nothing should change execution-wise, therefore there is nothing to optimize execution-wise. If you're worried about the type of the parameter you've requested, you can always explicitly store it in a different CGFloat before operating on it.

CodaFi
  • 43,043
  • 8
  • 107
  • 153
0

The machine works with memory. At the end all the variable that you use are just raw bytes.

Then why do Objective-C have types? To protect the programmer at compile time, showing errors and warnings.

At runtime all the operations that you do are made on the memory, so you don't need to worry about the overhead of casts.

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187