Skip to content

Commit 259e365

Browse files
committed
perf(android): Don't refresh memory statistics too often
1 parent 39a7e70 commit 259e365

File tree

1 file changed

+37
-8
lines changed

1 file changed

+37
-8
lines changed

src/Uno.UWP/System/MemoryManager.Android.cs

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using System;
1+
#nullable enable
2+
3+
using System;
24
using Android.OS;
35
using Android.App;
46
using Uno.UI;
@@ -7,25 +9,52 @@ namespace Windows.System
79
{
810
public partial class MemoryManager
911
{
12+
private static ulong _appMemoryUsage;
13+
private static ulong _appMemoryUsageLimit;
14+
15+
private static Debug.MemoryInfo? _mi;
16+
private static ActivityManager.MemoryInfo? _memoryInfo;
17+
private static global::System.Diagnostics.Stopwatch _updateWatch = global::System.Diagnostics.Stopwatch.StartNew();
18+
private static long _lastUpdate = long.MinValue;
19+
20+
private readonly static long _updateResolution = global::System.Diagnostics.Stopwatch.Frequency;
21+
1022
public static ulong AppMemoryUsage
1123
{
1224
get
1325
{
14-
Debug.MemoryInfo mi = new Debug.MemoryInfo();
15-
Debug.GetMemoryInfo(mi);
16-
var totalMemory = mi.TotalPss * 1024;
17-
return (ulong)totalMemory;
26+
Update();
27+
28+
return _appMemoryUsage;
1829
}
1930
}
2031

2132
public static ulong AppMemoryUsageLimit
2233
{
2334
get
2435
{
25-
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
26-
ActivityManager.FromContext(ContextHelper.Current)?.GetMemoryInfo(memoryInfo);
36+
Update();
37+
38+
return _appMemoryUsageLimit;
39+
}
40+
}
41+
42+
private static void Update()
43+
{
44+
var now = _updateWatch.ElapsedTicks;
45+
if (now - _lastUpdate > _updateResolution)
46+
{
47+
_lastUpdate = now;
48+
49+
_mi ??= new Debug.MemoryInfo();
50+
Debug.GetMemoryInfo(_mi);
51+
var totalMemory = _mi.TotalPss * 1024;
52+
_appMemoryUsage = (ulong)totalMemory;
53+
54+
_memoryInfo ??= new ActivityManager.MemoryInfo();
55+
ActivityManager.FromContext(ContextHelper.Current)?.GetMemoryInfo(_memoryInfo);
2756

28-
return AppMemoryUsage + (ulong)memoryInfo.AvailMem - (ulong)memoryInfo.Threshold;
57+
_appMemoryUsageLimit = _appMemoryUsage + (ulong)_memoryInfo.AvailMem - (ulong)_memoryInfo.Threshold;
2958
}
3059
}
3160
}

0 commit comments

Comments
 (0)