C#如何对String中的Contact/Join方法进行优化的
bigegpt 2024-09-22 00:39 3 浏览
起因
在更新.Net源码时发现有对String.Join做性能优化.便看了一下是如何优化的.来看这个代码提交.
阅读String.Join方法源码
public static string Join<T>(char separator, IEnumerable<T> values) =>
JoinCore(MemoryMarshal.CreateReadOnlySpan(ref separator, 1), values);
public static string Join<T>(string? separator, IEnumerable<T> values) =>
JoinCore(separator.AsSpan(), values);
private static string JoinCore<T>(ReadOnlySpan<char> separator, IEnumerable<T> values)
{
if (typeof(T) == typeof(string)) //如果类型是字符串,则优先处理
{
if (values is List<string?> valuesList) //如果是List<string>
{
return JoinCore(separator, CollectionsMarshal.AsSpan(valuesList));
}
if (values is string?[] valuesArray) //如果是string数组
{
return JoinCore(separator, new ReadOnlySpan<string?>(valuesArray));
}
}
if (values == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
}
//如果是其他类型,进行遍历
using (IEnumerator<T> en = values.GetEnumerator())
{
if (!en.MoveNext())
{
return Empty;
}
T currentValue = en.Current;
string? firstString = currentValue?.ToString(); //如果调用类型的ToString方法
if (!en.MoveNext())
{
return firstString ?? Empty;
}
//这里使用栈,预先分配256字节,将在栈上分配字符数组,传递给ValueStringBuilder
//这里先不说ValueStringBuilder,下边会源码进行解析
var result = new ValueStringBuilder(stackalloc char[256]);
result.Append(firstString);
do
{
currentValue = en.Current;
result.Append(separator);
if (currentValue != null)
{
result.Append(currentValue.ToString());
}
}
while (en.MoveNext());
return result.ToString();
}
}
private static string JoinCore(ReadOnlySpan<char> separator, ReadOnlySpan<string?> values)
{
if (values.Length <= 1)
{
return values.IsEmpty ?
Empty :
values[0] ?? Empty;
}
long totalSeparatorsLength = (long)(values.Length - 1) * separator.Length;
if (totalSeparatorsLength > int.MaxValue)
{
ThrowHelper.ThrowOutOfMemoryException();
}
int totalLength = (int)totalSeparatorsLength;
//计算List或者数组中的每个字符串的长度
foreach (string? value in values)
{
if (value != null)
{
totalLength += value.Length;
if (totalLength < 0) // Check for overflow
{
ThrowHelper.ThrowOutOfMemoryException();
}
}
}
//根据计算出的总长度进行内存分配, FastAllocateString是运行时方法,不是c#编写
string result = FastAllocateString(totalLength);
int copiedLength = 0;
for (int i = 0; i < values.Length; i++)
{
if (values[i] is string value)
{
int valueLen = value.Length;
if (valueLen > totalLength - copiedLength)
{
copiedLength = -1;
break;
}
//1. 将List或者数组的内容填充,分配好的result中
FillStringChecked(result, copiedLength, value);
copiedLength += valueLen;
}
//2.将分隔符填充到result
if (i < values.Length - 1)
{
//关于Unsafe <<在.Net Core中使用Span>>有提到
ref char dest = ref Unsafe.Add(ref result._firstChar, copiedLength);
//2.1 如果分隔符的长度为1,直接填充
if (separator.Length == 1)
{
dest = separator[0];
}
else
{
//2.2 如果分隔符不为1,则通过span根据长度进行填充
separator.CopyTo(new Span<char>(ref dest, separator.Length));
}
copiedLength += separator.Length;
}
}
return copiedLength == totalLength ?
result :
JoinCore(separator, values.ToArray().AsSpan());
}
阅读String.Concat方法源码
因为Concat重载方法比较多,这里只是列出3个Concat方法.
public static string Concat(IEnumerable<string?> values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
using (IEnumerator<string?> en = values.GetEnumerator())
{
if (!en.MoveNext())
return string.Empty;
string? firstValue = en.Current;
if (!en.MoveNext())
{
return firstValue ?? string.Empty;
}
//这里依然使用栈,这里先不说ValueStringBuilder
var result = new ValueStringBuilder(stackalloc char[256]);
result.Append(firstValue);
do
{
result.Append(en.Current);
}
while (en.MoveNext());
return result.ToString();
}
}
public static string Concat(string? str0, string? str1)
{
if (IsNullOrEmpty(str0))
{
if (IsNullOrEmpty(str1))
{
return string.Empty;
}
return str1;
}
if (IsNullOrEmpty(str1))
{
return str0;
}
int str0Length = str0.Length;
string result = FastAllocateString(str0Length + str1.Length); //计算两个字符串的长度,分配内存空间
FillStringChecked(result, 0, str0); //将第一个字符串拷贝到新分配的字符串result中
FillStringChecked(result, str0Length, str1); //将第二个字符串拷贝到新分配的字符串result中
return result;
}
public static string Concat(params string?[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
if (values.Length <= 1)
{
return values.Length == 0 ?
string.Empty :
values[0] ?? string.Empty;
}
// Sum the lengths of all input strings
//1. 计算字符串数组中的每个字符串的长度
long totalLengthLong = 0;
for (int i = 0; i < values.Length; i++)
{
string? value = values[i];
if (value != null)
{
totalLengthLong += value.Length;
}
}
// If it's too long, fail, or if it's empty, return an empty string.
if (totalLengthLong > int.MaxValue)
{
throw new OutOfMemoryException();
}
int totalLength = (int)totalLengthLong;
if (totalLength == 0)
{
return string.Empty;
}
//根据计算出的所有字符串的长度,分配内存空间
string result = FastAllocateString(totalLength);
int copiedLength = 0;
for (int i = 0; i < values.Length; i++)
{
string? value = values[i];
if (!string.IsNullOrEmpty(value))
{
int valueLen = value.Length;
if (valueLen > totalLength - copiedLength)
{
copiedLength = -1;
break;
}
//依次进行填充字符串内容
FillStringChecked(result, copiedLength, value);
copiedLength += valueLen;
}
}
return copiedLength == totalLength ? result : Concat((string?[])values.Clone());
}
来阅读ValueStringBuilder源码
ValueStringBuilder类是用internal标记的,意味着在我们的项目中无法直接使用,但不妨碍我们对ValueStringBuilder源码的学习.
//使用internal修饰表示在程序集内部使用
//使用struct,说明ValueStringBuilder为结构体,在struct前面使用ref声明,表示该结构体实现接口,也不能装箱,最典型的就是Span也是这样使用的
internal ref partial struct ValueStringBuilder
{
//在使用数组池,从数组池租用空间
private char[]? _arrayToReturnToPool;
//指向字符串第一个字符串,记录字符串的大小
private Span<char> _chars;
//存放内容记录位置
private int _pos;
//通过构造函数将字符串内容指向Span类型的_chars,不管内容是否来自栈上,还是堆上
//如果初始化内容来自栈,长度的不够,还是通过数组池租用空间,在将内容拷贝到_arrayToReturnToPool
public ValueStringBuilder(Span<char> initialBuffer)
{
_arrayToReturnToPool = null;
_chars = initialBuffer;
_pos = 0;
}
//如果直接通过构造函数指定初始化长度,直接通过数组池租用空间
public ValueStringBuilder(int initialCapacity)
{
_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
_chars = _arrayToReturnToPool;
_pos = 0;
}
//将字符串内容进行追加
public void Append(string? s)
{
if (s == null)
{
return;
}
int pos = _pos;
//如果当前字符串是一个字符时直接修改内容和位置
if (s.Length == 1 && (uint)pos < (uint)_chars.Length) //
{
_chars[pos] = s[0];
_pos = pos + 1;
}
else
{
AppendSlow(s);
}
}
//追加字符串
private void AppendSlow(string s)
{
int pos = _pos;
if (pos > _chars.Length - s.Length) //判断空间是否够用,不够用,重新分配空间
{
Grow(s.Length);
}
//将新的字符串追加到_chars,修改字符串的位置
s
#if !NET6_0_OR_GREATER
.AsSpan()
#endif
.CopyTo(_chars.Slice(pos));
_pos += s.Length;
}
//当空间不够用的时候调用
private void Grow(int additionalCapacityBeyondPos)
{
//重新调整数组池租用空间,大小为当前字符串的2倍,如果当前位置加要增加字符串的长度要大于当前字符串的长度2倍的话,则大小为 当前位置加要增加字符串的长度
char[] poolArray = ArrayPool<char>.Shared.Rent((int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), (uint)_chars.Length * 2));
//将内容拷贝到从数组池租用的新的字符数组中
_chars.Slice(0, _pos).CopyTo(poolArray);
//获取数组池指向老地址
char[]? toReturn = _arrayToReturnToPool;
//将新的租用字符数组指向_chars和_arrayToReturnToPool
_chars = _arrayToReturnToPool = poolArray;
if (toReturn != null)
{
//在将老的指向空间进行归还
ArrayPool<char>.Shared.Return(toReturn);
}
}
}
阅读FillStringChecked源码
private static void FillStringChecked(string dest, int destPos, string src)
{
Debug.Assert(dest != null);
Debug.Assert(src != null);
if (src.Length > dest.Length - destPos)
{
throw new IndexOutOfRangeException();
}
//内部有优化,这里就不是Memmove源码了
Buffer.Memmove(
destination: ref Unsafe.Add(ref dest._firstChar, destPos),
source: ref src._firstChar,
elementCount: (uint)src.Length);
}
结论
不管Join还是Contact,为了提高性能使用:
- 减少内存分配的次数
- 使用Span尽量避免生成临时的字符串.
- 使用运行时方法FastAllocateString进行了堆空间快速分配
- 使用栈内存,减少堆空间的分配,降低GC的压力
相关推荐
- pyproject.toml到底是什么东西?(py trim)
-
最近,在Twitter上有一个Python项目的维护者,他的项目因为构建失败而出现了一些bug(这个特别的项目不提供wheel,只提供sdist)。最终,发现这个bug是由于这个项目使用了一个pypr...
- BDP服务平台SDK for Python3发布(bdp数据平台)
-
下载地址https://github.com/imysm/opends-sdk-python3.git说明最近在开发和bdp平台有关的项目,用到了bdp的python的sdk,但是官方是基于p...
- Python-for-Android (p4a):(python-for-android p4a windows)
-
一、Python-for-Android(p4a)简介Python-for-Android(p4a),一个强大的开发工具,能够将你的Python应用程序打包成可在Android设备上运行...
- Qt for Python—Qt Designer 概览
-
前言本系列第三篇文章(QtforPython学习笔记—应用程序初探)、第四篇文章(QtforPython学习笔记—应用程序再探)中均是使用纯代码方式来开发PySide6GUI应用程序...
- Python:判断质数(jmu-python-判断质数)
-
#Python:判断质数defisPrime(n):foriinrange(2,n):ifn%i==0:return0re...
- 为什么那么多人讨厌Python(为什么python这么难)
-
Python那么棒,为什么那么多人讨厌它呢?我整理了一下,主要有这些原因:用缩进替代大括号许多人抱怨Python完全依赖于缩进来创建代码块,代码多一点就很难看到函数在哪里结束,那么你就需要把一个函数拆...
- 一文了解 Python 中带有 else 的循环语句 for-else/while-else
-
在本文中,我们将向您介绍如何在python中使用带有else的for/while循环语句。可能许多人对循环和else一起使用感到困惑,因为在if-else选择结构中else正常...
- python的numpy向量化语句为什么会比for快?
-
我们先来看看,python之类语言的for循环,和其它语言相比,额外付出了什么。我们知道,python是解释执行的。举例来说,执行x=1234+5678,对编译型语言,是从内存读入两个shor...
- 开眼界!Python遍历文件可以这样做
-
来源:【公众号】Python技术Python对于文件夹或者文件的遍历一般有两种操作方法,一种是至二级利用其封装好的walk方法操作:import osfor root,d...
- 告别简单format()!Python Formatter类让你的代码更专业
-
Python中Formatter类是string模块中的一个重要类,它实现了Python字符串格式化的底层机制,允许开发者创建自定义的格式化行为。通过深入理解Formatter类的工作原理和使用方法,...
- python学习——038如何将for循环改写成列表推导式
-
在Python里,列表推导式是一种能够简洁生成列表的表达式,可用于替换普通的for循环。下面是列表推导式的基本语法和常见应用场景。基本语法result=[]foriteminite...
- 详谈for循环和while循环的区别(for循环语句与while循环语句有什么区别)
-
初九,潜龙勿用在刚开始使用python循环语句时,经常会遇到for循环和while循环的混用,不清楚该如何选择;今天就对这2个循环语句做深入的分析,让大家更好地了解这2个循环语句以方便后续学习的加深。...
- Python编程基础:循环结构for和while
-
Python中的循环结构包括两个,一是遍历循环(for循环),一是条件循环(while循环)。遍历循环遍历循环(for循环)会挨个访问序列或可迭代对象的元素,并执行里面的代码块。foriinra...
- 学习编程第154天 python编程 for循环输出菱形图
-
今天学习的是刘金玉老师零基础Python教程第38期,主要内容是python编程for循环输出菱形※。(一)利用for循环输出菱形形状的*号图形1.思路:将菱形分解为上下两个部分三角形图案,分别利用...
- python 10个堪称完美的for循环实践
-
在Python中,for循环的高效使用能显著提升代码性能和可读性。以下是10个堪称完美的for循环实践,涵盖数据处理、算法优化和Pythonic编程风格:1.遍历列表同时获取索引(enumerate...
- 一周热门
- 最近发表
-
- pyproject.toml到底是什么东西?(py trim)
- BDP服务平台SDK for Python3发布(bdp数据平台)
- Python-for-Android (p4a):(python-for-android p4a windows)
- Qt for Python—Qt Designer 概览
- Python:判断质数(jmu-python-判断质数)
- 为什么那么多人讨厌Python(为什么python这么难)
- 一文了解 Python 中带有 else 的循环语句 for-else/while-else
- python的numpy向量化语句为什么会比for快?
- 开眼界!Python遍历文件可以这样做
- 告别简单format()!Python Formatter类让你的代码更专业
- 标签列表
-
- mybatiscollection (79)
- mqtt服务器 (88)
- keyerror (78)
- c#map (65)
- xftp6 (83)
- bt搜索 (75)
- c#var (76)
- xcode-select (66)
- mysql授权 (74)
- 下载测试 (70)
- linuxlink (65)
- pythonwget (67)
- androidinclude (65)
- libcrypto.so (74)
- linux安装minio (74)
- ubuntuunzip (67)
- vscode使用技巧 (83)
- secure-file-priv (67)
- vue阻止冒泡 (67)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)