4

I'm writing a java application that transforms numbers (long) into a small set of result objects. This mapping process is very critical to the app's performance as it is needed very often.

public static Object computeResult(long input) {
    Object result;
    // ... calculate
    return result;
}

There are about 150,000,000 different key objects, and about 3,000 distinct values. The transformation from the input number (long) to the output (immutable object) can be computed by my algorithm with a speed of 4,000,000 transformations per second. (using 4 threads)

I would like to cache the mapping of the 150M different possible inputs to make the translation even faster but i found some difficulties creating such a cache:

public class Cache {
    private static long[] sortedInputs; // 150M length
    private static Object[] results; // 150M length

    public static Object lookupCachedResult(long input) {
        int index = Arrays.binarySearch(sortedInputs, input);
        return results[index];
    }
}

i tried to create two arrays with a length of 150M. the first array holds all possible input longs, and it is sorted numerically. the second array holds a reference to one of the 3000 distinct, precalculated result objects at the index corresponding to the first array's input.

to get to the cached result, i do a binary search for the input number on the first array. the cached result is then looked up in the second array at the same index.

sadly, this cache method is not faster than computing the results. not even half, only about 1.5M lookups per second. (also using 4 threads)

Can anyone think of a faster way to cache results in such a scenario?

I doubt there is a database engine that is able to answer more than 4,000,000 queries per second on, let's say an average workstation.

9
  • 1
    did you try TreeMap<Long, Object>? and you cache is almost read-only, right?
    – Jason Hu
    Jun 8, 2015 at 20:47
  • What do you mean with a binary search? Insertion in this array will take a very long time... Jun 8, 2015 at 20:49
  • 3
    I would say HashMap rather than TreeMap - there is no need to order the keys. Lookup should be O(1) so theoretically not affected by size. Jun 8, 2015 at 20:49
  • 4M/sec is a fairly large number, i doubt your algo is not so complex enough that your bottle neck. think about it, 500 clock cycle per object is not large. your program is slow is due to the large dataset. if you want to make your app looks responsive, there are other technique can be deployed, though.
    – Jason Hu
    Jun 8, 2015 at 20:50
  • 1
    I would agree with HashMap over TreeMap for speed, since a TreeMap is is essentially going to be the same sort of lookup as using binary search on the array.
    – neuronaut
    Jun 8, 2015 at 20:51

2 Answers 2

1

Hashing is the way to go here, but I would avoid using HashMap, as it only works with objects, i.e. must build a Long each time you insert a long, which can slow it down. Maybe this performance issue is not significant due to JIT, but I would recommend at least to try the following and measure performance against the HashMap-variant:

Save your longs in a long-array of some length n > 3000 and do the hashing by hand via a very simple hash-function (and thus efficient) like index = key % n. Since you know your 3000 possible values before hand you can empirically find an array-length n such that this trivial hash-function won't cause collisions. So you circumvent rehashing etc. and have true O(1)-performance.

Secondly I would recommend you to look at Java-numerical libraries like

Both are backed by native Lapack and BLAS implementations that are usually highly optimized by very smart people. Maybe you can formulate your algorithm in terms of matrix/vector-algebra such that it computes the whole long-array at one time (or chunk-wise).

4
  • thx. i tried to avoid boxing the input longs to objects by using a long[] in my described try. the input numbers are products of prime numbers, i am not sure how to create a collision-free hash function for such values, they can be very large, how do i compress them to unique integers? i dont fully understand how the second paragraph would result in a list of unique integers, please explain.
    – andre.r
    Jun 8, 2015 at 22:27
  • Sorry, when I mentioned the 3000 I mixed up your numbers (overlooked that 3000 refers to the result-values). So in fact the lookup-array must be much larger. My suggestion with "empirically" meant to just try some values for n automatically and observe whether harmful collisions occur. Since your mapping compresses the value-space drastically, some collisions might not be harmful, as they might map different inputs to the right shared result. However using this intentionally would go into compression-theory and be more complex than just using ordinary hashing.
    – stewori
    Jun 11, 2015 at 12:39
  • I am also not an expert in constructing hash-functions. The thing with the prime-numbers still sounds promising. At least it rules out some values for n. E.g. n should likely be no number composed of prime-factors that occur in several values in the same combination. To tell whether this can be exploited even further to find a suitable n, more detail would be needed (can occur prime-factors with multiplicity? Are there prime numbers that don't occur as factors?). I guess, n-values composed of prime-factors not-occurring in the inputs would be good candidates. But this is only a guess, sorry.
    – stewori
    Jun 11, 2015 at 12:47
  • Another thought: I you save the input-value beneath each result (i.e. in another array with corresponding indices) you can even use n's with moderate collisions as you can trivially and efficiently confirm the lookup. If the input doesn't match, just compute the right result via computResult. This way an n mapping the vast majority without collision would be sufficient. (However in this case you could not benefit from non-harmful collisions unless you save a list of input-values beneth the result, but this would get slower and complicated again.)
    – stewori
    Jun 11, 2015 at 13:06
1

There are about 150,000,000 different key objects, and about 3,000 distinct values.

With the few values, you should ensure that they get re-used (unless they're pretty small objects). For this an Interner is perfect (though you can run your own).

i tried hashmap and treemap, both attempts ended in an outOfMemoryError.

There's a huge memory overhead for both of them. And there isn't much point is using a TreeMap as it uses a sort of binary search which you've already tried.

There are at least three implementations of a long-to-object-map available, google for "primitive collections". This should use slightly more memory than your two arrays. With hashing being usually O(1) (let's ignore the worst case as there's no reason for it to happen, is it?) and much better memory locality, it'll beat(*) your binary search by a factor of 20. You binary search needs log2(150e6), i.e., about 27 steps and hashing may need on the average maybe two. This depends on how tightly you pack the hash table; this is usually a parameter given when it gets created.

In case you run your own (which you most probably shouldn't), I'd suggest to use an array of size 1 << 28, i.e., 268435456 entries, so that you can use bitwise operations for indexing.


(*) Such predictions are hard, but I'm sure it's worth trying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.