Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[EC87] Use collection indexer #42

Closed
Djoums opened this issue Apr 29, 2024 · 0 comments · Fixed by #41
Closed

[EC87] Use collection indexer #42

Djoums opened this issue Apr 29, 2024 · 0 comments · Fixed by #41
Assignees
Labels
🗃️ rule rule improvment or rule development or bug 🚀 enhancement New feature or request

Comments

@Djoums
Copy link
Collaborator

Djoums commented Apr 29, 2024

Category : Performance

Severity : Warning

Why is this an issue ?

Linq methods like First(), Last() and ElementAt() can be necessary on enumerable types that don't have an indexer. But for those that do, direct index access is a lot cheaper at runtime than their Linq counterpart and should be used instead.

When can it be ignored ?

This rule shouldn't be ignored.

Examples

public static void Test(int[] arr)
{
    int first = arr.First(); // Non-compliant, use arr[0]
    int last = arr.Last(); // Non-compliant, use arr[^1], or arr[arr.Length - 1] if C# < 8
    int third = arr.ElementAt(2); // Non-compliant, use arr[2]
}

Asm code analysis

Using this C# code :

public static int FirstNonCompliant(int[] arr) => arr.First();
public static int FirstCompliant(int[] arr) => arr[0];

We get the following compiled asm code, showing the clear difference between the 2.

FirstNonCompliant(Int32[])
    L0000: push ebp
    L0001: mov ebp, esp
    L0003: push eax
    L0004: lea edx, [ebp-4]
    L0007: call dword ptr [0x258beb50]
    L000d: cmp byte ptr [ebp-4], 0
    L0011: je short L0017
    L0013: mov esp, ebp
    L0015: pop ebp
    L0016: ret
    L0017: call dword ptr [0xc9677c8]
    L001d: int3

FirstCompliant(Int32[])
    L0000: cmp dword ptr [ecx+4], 0
    L0004: jbe short L000a
    L0006: mov eax, [ecx+8]
    L0009: ret
    L000a: call 0x73794810
    L000f: int3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🗃️ rule rule improvment or rule development or bug 🚀 enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant