mtbc: maze C (black-yellow)
[personal profile] mtbc
At work I program in Java 7 mostly. I was asked to add some statistics-gathering to some code that gets called a lot so performance is key. After some initial test runs, back-of-the-envelope calculations about for how long our servers may run, etc., I did not feel safe in assuming that even a eight-byte long counter would never wrap around. In practice, I do not think a production server facing a continuously heavy workload during many years' uptime would come close to overflowing my long but I am used to having so much margin to work with that I do not even have to think about the issue.

A surprising discovery for me is that Java 7 does not offer efficient incrementing of arbitrarily large integers. Coming from a functional programming background I appreciate immutable values but I also appreciate compilers that can optimize much of the heap allocation out of the native code they generate. I have far less faith in what Java does, or indeed may do, with BigInteger, and people on the Internet already seem to have done some performance testing.

Fortunately, not all surprising discoveries are bad. It also turns out to be easy to increment an arbitrarily large integer with few heap allocations by storing it as a byte array, here named count:
for (int index = count.length; index > 0;)
  if (++count[--index] != 0)
    return;
count = new byte[count.length + 1];
count[0] = 1;
To log the statistic readably it suffices to return new BigInteger(1, count).

Date: 2017-11-29 06:54 pm (UTC)
From: [personal profile] goldibehr
While it works fine, BigInteger seems like overkill. You could quickly make your own 128-bit "LongLong" class holding 2 long values. That object would far less expensive to increment than the code you show.

How many increments per second does the problem need?

Date: 2017-11-30 05:47 pm (UTC)
From: [personal profile] goldibehr
Yeah, I misunderstood. I thought you were creating a new BigInteger object every time you incremented.

Profile

mtbc: photograph of me (Default)
Mark T. B. Carroll

May 2025

S M T W T F S
    123
456 78910
11 121314 15 16 17
18 19202122 2324
25262728293031

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 1st, 2025 07:38 pm
Powered by Dreamwidth Studios