Skip to content

Conversation

LeaFrock
Copy link

@LeaFrock LeaFrock commented Aug 9, 2022

@yndu13 您好,该项目涉及到阿里云SDK,希望能为本项目做一点贡献,提升.NET SDK的质量。

以下是PR具体内容。其中“可选的优化”因改动较大并未实现,属个人意见供贵方参考。

StringUtils

  • 重写查找子字符串数量的实现,实现0内存分配下更好的性能表现

  • 可选的优化:该方法仅用于StringUtils.SubStringCount(node[0].OuterXml, realName) > 1),那么判断字符串大于1即可停止查找。

 internal static bool SubStringCountGreaterThan(string str, string subString, int count) { if (subString.Length < 1) { //if subString is Empty, let's throw an ArgumentException similar to `String.Replace()`. throw new ArgumentException("The length of subString cannot be zero."); } int repeat = 0, index = str.IndexOf(subString, StringComparison.Ordinal); while (index >= 0) { repeat++; if(repeat > count) { return true; } index = str.IndexOf(subString, index + subString.Length, StringComparison.Ordinal); } return false; }

XmlUtil

  • 将字典的ContainsKey修改为TryGetValue,减少多余的Hash查找

  • 在条件允许的情况下,指定初始化的字典Capacity,减少底层扩容带来的性能损耗和内存浪费

  • 使用string.IsNullOrWhiteSpace替换string.IsNullOrEmptystring.Trim,减少特定情况下的内存分配

  • 使用LinqFirst()替换ToList()[0],减少内存分配

  • 使用GetCustomAttribute<T>泛型重载方法,精简代码

  • 可选的优化:mapObj方法里较多的if-else判断propertyType,一方面时间复杂度会随着分支数呈现O(n)级别的上升,另一方面会影响CPU的指令预测并增加Cache Miss。或许可采用如下实现:

 private readonly static Dictionary<Type, Func<string, object>> SupportTypeMap = new Dictionary<Type, Func<string, object>>() { { typeof(int?), s => Convert.ToInt32(s) }, { typeof(long?), s => Convert.ToInt64(s) }, { typeof(float?), s => Convert.ToSingle(s) }, { typeof(double?), s => Convert.ToDouble(s) }, { typeof(bool?), s => Convert.ToBoolean(s) }, { typeof(short?), s => Convert.ToInt16(s) }, { typeof(ushort?), s => Convert.ToUInt16(s) }, { typeof(uint?), s => Convert.ToUInt32(s) }, { typeof(ulong?), s => Convert.ToUInt64(s) }, }; private static object mapObj2(Type propertyType, string value) { Func<string, object> factory; if (SupportTypeMap.TryGetValue(propertyType, out factory)) { return factory.Invoke(value); } //if(!propertyType.IsAssignableFrom(typeof(IConvertible))) //{ // throw new ArgumentException("xxx"); //} return Convert.ChangeType(value, propertyType); }
@CLAassistant
Copy link

CLAassistant commented Aug 9, 2022

CLA assistant check
All committers have signed the CLA.

@yndu13 yndu13 added the help wanted Extra attention is needed label Jun 30, 2023
@yndu13 yndu13 changed the title CSharp模块性能优化 [WIP]CSharp模块性能优化 Jun 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

help wanted Extra attention is needed

3 participants