0

My problem: I'm downloading huge data from the database for JFreeChart. I want to optimize data memory usage without using a primitive table.

Working with collections requires objects usage. I'm wondering if I can optimize memory usage using primitive Stream like IntStream instead of for example LinkedList<Integer>.

I don't know how to make a reliable benchmark.

Keyur
  • 180
  • 1
  • 5
  • 20
MilczekT1
  • 3
  • 2
  • 2
    Write good code first, optimize later if it needs it. Pre-optimization is a mistake. – lucasvw Jul 06 '17 at 12:49
  • probably the *only* reliable way to measure the size of an object, but takes a while to get used to http://openjdk.java.net/projects/code-tools/jol/ – Eugene Jul 06 '17 at 12:59
  • `IntStream` is a "flyweight object". In a sense, any Java stream, primitive or otherwise, only ever "has" a single piece of data you can access by `peek`ing it. Considering you use database in jdbc form, its `ResultSet` can also be viewed as an iterator of sorts, which you indeed can build a stream out of, but this is just one solution of many. You may even want to build all chart data and trim it in database directly without wasting cycles doing all processing in Java. – M. Prokhorov Jul 06 '17 at 13:04

1 Answers1

1

If your starting point is a LinkedList<Integer>, just replacing it with ArrayList<Integer> will reduce the memory consumption significantly, as explained in When to use LinkedList over ArrayList?. Since boxed integers are small objects and some of them will even be reused when boxing the same value, the graphs of this answer have significance.

If you want to have it simpler, just use int[]. If you need something you can fill incrementally, the Stream API has indeed an option. Use IntStream.builder() to get an IntStream.Builder to which you can repeatedly add new int values. Once it contains all values, you can call build().toArray() on it to get an int[] array containing all values or you can directly perform filtering and aggregate operations on the IntStream returned by build() (if you can express the aggregate operation as reduction).

Holger
  • 285,553
  • 42
  • 434
  • 765