MPAndroidChart icon indicating copy to clipboard operation
MPAndroidChart copied to clipboard

Memory management

Open KaiJun-Ma opened this issue 6 months ago • 1 comments

Here is my code. I found that whenever I call 'invalidate', the memory keeps growing, and I need to update the chart frequently. Version 3.1.0

public void updateChart(float value) {
        // Add new data point
        try {
            Entry entry = mEntryPool.obtain();
            entry.setX(xAxis);
            entry.setY(value);
            entries.add(entry);

            // Notify the chart of data change and refresh
            if (System.currentTimeMillis()-lastRefreshTime > refreshDivision){
                dataSet.notifyDataSetChanged();
                lineData.notifyDataChanged();
                chart.notifyDataSetChanged();
                chart.invalidate();
                lastRefreshTime = System.currentTimeMillis();
            }

           // Keep only the latest MAX_DATA_POINTS
            if (entries.size() >= MAX_DATA_POINTS) {
                entry = entries.remove(0);
                mEntryPool.recycle(entry);
            }

            xAxis++;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

KaiJun-Ma avatar Jun 11 '25 02:06 KaiJun-Ma

Imporved code :

public void updateChart(float value) {
    try {
        // Remove oldest entry first if we're at capacity
        Entry recycledEntry = null;
        if (entries.size() >= MAX_DATA_POINTS) {
            recycledEntry = entries.remove(0);
        }
        
        // Add new data point (reuse recycled entry if available)
        Entry entry;
        if (recycledEntry != null) {
            entry = recycledEntry;
            entry.setX(xAxis);
            entry.setY(value);
        } else {
            entry = mEntryPool.obtain();
            entry.setX(xAxis);
            entry.setY(value);
        }
        entries.add(entry);
        
        // Only recycle if we actually removed an entry and didn't reuse it
        if (recycledEntry != null) {
            // Entry was reused, no need to recycle
        }

        // Throttled refresh with single notification
        if (System.currentTimeMillis() - lastRefreshTime > refreshDivision) {
            // Use only one notification method
            chart.notifyDataSetChanged();
            chart.invalidate();
            lastRefreshTime = System.currentTimeMillis();
        }

        xAxis++;
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

Yash-xoxo avatar Aug 13 '25 05:08 Yash-xoxo