Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/Tizen.Sensor/Tizen.Sensor/Sensor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public abstract class Sensor : IDisposable
private SensorPausePolicy _pausePolicy = SensorPausePolicy.None;
private IntPtr _sensorHandle = IntPtr.Zero;
private IntPtr _listenerHandle = IntPtr.Zero;
private static readonly int s_sensorEventStructSize = Marshal.SizeOf<Interop.SensorEventStruct>();
internal IList<Interop.SensorEventStruct> BatchedEvents { get; set; } = new List<Interop.SensorEventStruct>();


Expand Down Expand Up @@ -89,11 +90,16 @@ internal void updateBatchEvents(IntPtr eventsPtr, uint events_count)
if (events_count >= 1)
{
BatchedEvents.Clear();
if (BatchedEvents is List<Interop.SensorEventStruct> list && list.Capacity < events_count)
{
list.Capacity = (int)events_count;
}

IntPtr currentPtr = eventsPtr;
for (int i = 0; i < events_count; i++)
{
BatchedEvents.Add(Interop.IntPtrToEventStruct(currentPtr));
currentPtr += Marshal.SizeOf<Interop.SensorEventStruct>();
currentPtr += s_sensorEventStructSize;
}
Comment on lines 99 to 103

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since updateBatchEvents is on a hot path and BatchedEvents is cleared and repopulated on every call, we can optimize memory allocations by ensuring the underlying List<T> has sufficient capacity before the loop. This avoids multiple internal array reallocations and copying overhead during the loop.

Since BatchedEvents is initialized as a List<Interop.SensorEventStruct>, we can cast it and set its Capacity if it is currently smaller than events_count.

                if (BatchedEvents is List<Interop.SensorEventStruct> list && list.Capacity < events_count)
                {
                    list.Capacity = (int)events_count;
                }

                for (int i = 0; i < events_count; i++)
                {
                    BatchedEvents.Add(Interop.IntPtrToEventStruct(currentPtr));
                    currentPtr += s_sensorEventStructSize;
                }

}
}
Expand Down
Loading