Learnt: Division in programming is inherently slower than multiplication

Was just wanting to comment on how I didn’t know multiplication is/can be faster than division. I’m now more curious as to why haha!

1 Like

I’m not expert on this but I had some exposure to it some time ago.

Multiplication is just repeated addition of a given quantity, right; so there are tricks that can optimize that. I don’t know all the tricks CPUs deploy for it in their instruction sets, but this is the kind of task you can quickly divide and conquer various ways. Division is different as the “subtractive” quantity you are trying to attain isn’t known (e.g. 2 * 25 = 25 + 25, but 50 / 2 = ? - ?). Maybe also has to do with things being commutative or not, so that the task can be broken down and rearranged more optimally and still get the same results.

I believe it used to be the case that integer multiplication was king of speed, then floating point muls, then division (either integer or floating point). As such, people would often flip division to a mul when given the choice… 50 / 2 == 50 * 0.5.

I don’t know how true that all is still today as I expect necessity and improvements have helped close the gap, possibly along with some compiler optimization involved too. I was first introduced to this all 20+ years ago when I first began dabbling with DX and GL and game dev, but haven’t really refreshed myself on it since, so I’d love to hear a more modern take on it.

2 Likes

That’s pretty much what I learnt when I was studied computer science. One thing to watch out for though is floating point precision errors that can crop up if you decide to multiply rather than divide.

It really comes down to how well your compiler can optimize your code though - some languages are better than others and if you do a search on StackExchange you’ll find numerous thread with various timing tests.

When it comes to calculations taking the square root is probably one of the worst offenders.

Personally, I just go for readability over performance in most cases. If there are performance issues with my game, it’s usually some bigger problem that’s causing them.

1 Like

Privacy & Terms