Skip to content

Commit

Permalink
[Xamarin.Android.Build.Tasks] Small refactoring to AddKeepAlives me…
Browse files Browse the repository at this point in the history
…thod (#8423)

The `method.Parameters.Count == 0` check should be faster than LINQ's `Any` call
(`CustomAttributes.Any`). So moved it first.

Moved some variables near their usage, particularly, `GetILProcessor` which may
allocate unnecessarily if `GC.KeepAlive(...)` call was already found. It's not a
big of problem though as it's not very common.
  • Loading branch information
Youssef1313 authored Oct 17, 2023
1 parent 03018e0 commit 2625783
Showing 1 changed file with 8 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -86,18 +86,13 @@ bool AddKeepAlives (TypeDefinition type)
{
bool changed = false;
foreach (MethodDefinition method in type.Methods) {
if (!method.CustomAttributes.Any (a => a.AttributeType.FullName == "Android.Runtime.RegisterAttribute"))
if (method.Parameters.Count == 0)
continue;

if (method.Parameters.Count == 0)
if (!method.CustomAttributes.Any (a => a.AttributeType.FullName == "Android.Runtime.RegisterAttribute"))
continue;

var processor = method.Body.GetILProcessor ();
var module = method.DeclaringType.Module;
var instructions = method.Body.Instructions;
var end = instructions.Last ();
if (end.Previous.OpCode == OpCodes.Endfinally)
end = end.Previous;

var found = false;
for (int off = Math.Max (0, instructions.Count - 6); off < instructions.Count; off++) {
Expand All @@ -111,6 +106,12 @@ bool AddKeepAlives (TypeDefinition type)
if (found)
continue;

var processor = method.Body.GetILProcessor ();
var module = method.DeclaringType.Module;
var end = instructions.Last ();
if (end.Previous.OpCode == OpCodes.Endfinally)
end = end.Previous;

for (int i = 0; i < method.Parameters.Count; i++) {
if (method.Parameters [i].ParameterType.IsValueType || method.Parameters [i].ParameterType.FullName == "System.String")
continue;
Expand Down

0 comments on commit 2625783

Please sign in to comment.