new BigInteger(String) performance / complexity

后端 未结 3 1987
猫巷女王i
猫巷女王i 2021-01-11 15:08

I\'m wondering about the performance/complexity of constructing BigInteger objects with the new BigInteger(String) constructor

3条回答
  •  一向
    一向 (楼主)
    2021-01-11 15:30

    Simplifying from the source somewhat, it's the case because in the "traditional" String parsing loop

    for each digit y from left to right:
      x = 10 * x + y
    

    you have the issue that 10 * x takes time linear in the length of x, unavoidably, and that length grows by more-or-less a constant factor for each digit, also unavoidably.

    (The actual implementation is somewhat smarter than this -- it tries to parse an int's worth of binary digits at a time, and so the actual multiplier in the loop is more likely 1 or 2 billion -- but yeah, it's still quadratic overall.)

    That said, a number with 10^6 digits is at least a googol, and that's bigger than any number I've heard of being used even for cryptographic purposes. You're parsing a string that takes two megabytes of memory. Yes, it'll take a while, but I suspect the JDK authors didn't see the point of optimizing for such a rare use case.

提交回复
热议问题