Question

I have a piece of code which goes like (vb.net or c# "language" is immaterial):

 Dim Counter As BigInteger = 0
 Serial = BigInteger.DivRem(Serial, 4, Counter)
 CountersList.Add(CInt(Counter))

Since I was making many of those division by 4, with very large positive integers (several hundred digits) and after receiving a few "out of memory exceptions", I went to give another reading to the documentation.

In the shift operator page I can read: "Languages that do not support custom operators can perform a bitwise left-shift operation by multiplying value by BigInteger.Pow(2, shift)."

So I though that the above code could, perhaps, improve this way (making explicit i am dividing by a power of 2):

Dim Counter As BigInteger = 0
Serial = BigInteger.DivRem(Serial, BigInteger.Pow(2, 2), Counter)
CountersList.Add(CInt(Counter))

My question.

  • In general, is there any advantage to explicitly use the BigInteger.Pow(), so that perhaps (?) the compiler knows it can perform shifts, instead of multiplication/division?

  • In my specific case, where I need to make the division by 4, and get both the result and the remainder, what is the best way to go ?

Was it helpful?

Solution

In general, is there any advantage to explicitly use the BigInteger.Pow(), so that perhaps (?) the compiler knows it can perform shifts, instead of multiplication/division?

There is no support for BigInteger in CIL (the intermediate language, i.e. assembly code, behind .NET's languages), so no, the compiler cannot optimize it. (Unless it had some very specific support for BigInteger in such a way to understand it can replace a 'divide by 4' by 'shift right by two bits' etc.)

In my specific case, where I need to make the division by 4, and get both the result and the remainder, what is the best way to go ?

You can use a sequence of And to get the remainder and >> to perform the division, e.g.:

Dim Remainder as BigInteger = Serial And New BigInteger(3)
Serial = Serial >> 2

(Note: Sorry for possible syntax errors, VB is not my language.)

However, I don't think the source of OutOfMemoryException are these trivial operations. Inspect the expection's stack trace to know where it's happening at the first place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top