Skip to content

CA1845 #24270

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

Merged
merged 9 commits into from
May 18, 2021
Merged

CA1845 #24270

Show file tree
Hide file tree
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
65 changes: 65 additions & 0 deletions docs/fundamentals/code-analysis/quality-rules/ca1845.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
title: "CA1845: Use span-based 'string.Concat' (analysis rule)"
description: "Learn about code analysis rule CA1845: Use span-based 'string.Concat'"
ms.date: 05/18/2021
ms.topic: reference
f1_keywords:
- "UseSpanBasedStringConcat"
- "CA1845"
helpviewer_keywords:
- "UseSpanBasedStringConcat"
- "CA1845"
author: NewellClark
dev_langs:
- CSharp
---
# CA1845: Use span-based 'string.Concat'

| | Value |
|-|-|
| **Rule ID** |CA1845|
| **Category** |[Performance](performance-warnings.md)|
| **Fix is breaking or non-breaking** |Non-breaking|

## Cause

This rule locates string-concatenation expressions that contain <xref:System.String.Substring%2A> calls and suggests replacing <xref:System.String.Substring%2A> with <xref:System.MemoryExtensions.AsSpan%2A> and using the span-based overload of <xref:System.String.Concat%2A?displayProperty=nameWithType>.

## Rule description

Calling `Substring` produces a copy of the extracted substring. By using `AsSpan` instead of `Substring` and calling the overload of `string.Concat` that accepts spans, you can eliminate the unnecessary string allocation.

## How to fix violations

To fix violations:

1. Replace the string concatenation with a call to `string.Concat`, and
2. Replace calls to `Substring` with calls to `AsSpan`.

The following code snippet shows examples of violations, and how to fix them.

```csharp
using System;

class Example
{
public void Method()
{
string text = "fwobz the fwutzle";

// Violation: allocations by Substring are wasteful.
string s1 = text.Substring(10) + "---" + text.Substring(0, 5);

// Fixed: using AsSpan avoids allocations of temporary strings.
string s2 = string.Concat(text.AsSpan(10), "---", text.AsSpan(0, 5));
}
}
```

## When to suppress warnings

Do not suppress warnings from this rule. There is no reason to use `Substring` over `AsSpan` when the extracted substring is only being passed to a method with a span-based equivalent.

## See also

- [Performance rules](performance-warnings.md)
1 change: 1 addition & 0 deletions docs/fundamentals/code-analysis/quality-rules/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ The following table lists code quality analysis rules.
> | [CA1837: Use `Environment.ProcessId` instead of `Process.GetCurrentProcess().Id`](ca1837.md) | `Environment.ProcessId` is simpler and faster than `Process.GetCurrentProcess().Id`. |
> | [CA1838: Avoid `StringBuilder` parameters for P/Invokes](ca1838.md) | Marshaling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshaling operation. |
> | [CA1841: Prefer Dictionary Contains methods](ca1841.md) | Calling `Contains` on the `Keys` or `Values` collection may often be more expensive than calling `ContainsKey` or `ContainsValue` on the dictionary itself. |
> | [CA1845: Use span-based 'string.Concat'](ca1845.md) | It is more efficient to use `AsSpan` and `string.Concat`, instead of `Substring` and a concatenation operator. |
> | [CA2000: Dispose objects before losing scope](ca2000.md) | Because an exceptional event might occur that will prevent the finalizer of an object from running, the object should be explicitly disposed before all references to it are out of scope. |
> |[CA2002: Do not lock on objects with weak identity](ca2002.md) |An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. |
> | [CA2007: Do not directly await a Task](ca2007.md) | An asynchronous method [awaits](../../../csharp/language-reference/operators/await.md) a <xref:System.Threading.Tasks.Task> directly. When an asynchronous method awaits a <xref:System.Threading.Tasks.Task> directly, continuation occurs in the same thread that created the task. This behavior can be costly in terms of performance and can result in a deadlock on the UI thread. Consider calling <xref:System.Threading.Tasks.Task.ConfigureAwait(System.Boolean)?displayProperty=nameWithType> to signal your intention for continuation. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,4 @@ Performance rules support high-performance libraries and applications.
| [CA1837: Use `Environment.ProcessId` instead of `Process.GetCurrentProcess().Id`](ca1837.md) | `Environment.ProcessId` is simpler and faster than `Process.GetCurrentProcess().Id`. |
| [CA1838: Avoid `StringBuilder` parameters for P/Invokes](ca1838.md) | Marshaling of `StringBuilder` always creates a native buffer copy, resulting in multiple allocations for one marshaling operation. |
| [CA1841: Prefer Dictionary Contains methods](ca1841.md) | Calling `Contains` on the `Keys` or `Values` collection may often be more expensive than calling `ContainsKey` or `ContainsValue` on the dictionary itself. |
| [CA1845: Use span-based 'string.Concat'](ca1845.md) | It is more efficient to use `AsSpan` and `string.Concat`, instead of `Substring` and a concatenation operator. |
2 changes: 2 additions & 0 deletions docs/fundamentals/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,8 @@ items:
href: code-analysis/quality-rules/ca1838.md
- name: CA1841
href: code-analysis/quality-rules/ca1841.md
- name: CA1845
href: code-analysis/quality-rules/ca1845.md
- name: SingleFile rules
items:
- name: Overview
Expand Down