Search code examples
swiftstringcastingstring-formatting

Is String formatting more expensive than casting a Double to an Int?


I have to choose between one of the two in a program I'm writing in Swift but I guess it doesn't really matter what programming language I'm using.

I know String formatting is very expensive and suspect it to be more expensive than casting a Double to an Int, but I'm not even sure and most importantly, as of now, I don't see why this is the case.

Also, what I'm trying to do here is to truncate a number and print it to the console without a decimal part (meaning that I don't want it to appear like this 0.0 but like this 0). What is the most efficient way of doing that?

Could someone enlighten me?

Here is the code (String formatting on the first line and casting on the second):

print(String(format: "%.0f", sender.value))

Int(sender.value)

Solution

  • This doesn't answer the proximate question, but hopefully counts as "enlightenment."

    The answer is: just stop worrying about micro-performance issues; about 99.999% of the time, they are a dangerous distraction. Focus instead on writing clear, readable code that is obviously correct. A program that is fast but wrong is infinitely worse than no program at all. On the other hand, a program that is correct but could be faster is still pretty darn good. When you are so good that your programs are correct all the time, then maybe it is time to start thinking about improving performance. Clear correct code can be optimized if it needs it; "clever" fast-but-wrong code can rarely be made correct without much more effort. (Case in point: your "faster" version discards information that might be important: the non-integral portion of the double. Maybe that's OK, maybe it's not -- you haven't said -- but it is the sort of mistake people often make when they let performance get ahead of correctness.)

    For your particular question, the dynamic is even worse, because there's only one reason to format a string -- which is to write it out to some IO channel. IO is already way more expensive that computation, so 99.999% of the time, it doesn't really matter if a small computation on the way to an IO is 5x or 10x more expensive.

    Further, much of what we "know" about performance ("I know String formatting is very expensive") is just lore, and often wrong or out of date. Be very, very suspicious about what non-experts say is "expensive".

    So the answer is "don't worry, do the clear, correct, readable thing."