gpt4 book ai didi

c# - 将方法变量作为参数传递以进行代码优化

转载 作者:行者123 更新时间:2023-11-30 22:07:55 28 4
gpt4 key购买 nike

我有一个方法

protected List<string> WrapInTwoLines(string text, int lineLimit)
{
///There will be always two lines even first line can be empty and whole data goes to 2nd line
string[] originalLines = text.Split(new string[] { " " }, StringSplitOptions.None);

List<string> wrappedLines = new List<string>();

StringBuilder actualLine = new StringBuilder();

int index=0;
while(actualLine.Length + originalLines[index].Length < lineLimit)
{
actualLine.AppendFormat("{0} ",originalLines[index]);
index++;
}
wrappedLines.Add(actualLine.ToString());
actualLine.Clear();

while (index < originalLines.Length)
{
actualLine.AppendFormat("{0} ",originalLines[index++]);
}
wrappedLines.Add(actualLine.ToString().TrimEnd(' '));
return wrappedLines;
}

在循环中被调用

for(int i=0; i< items.Count; i++)
{
length += items[i].Length + 2;
if (length > CHAR_LENGTH)
{
var list = WrapInTwoLines(items[i], CHAR_LENGTH - (length - items[i].Length + 2));
subtitlesList.Add(s.Append(list[0]).ToString());

s = new StringBuilder().AppendFormat("{0}{1}",list[1],separator);
length = s.Length;
}
else
{
s.AppendFormat("{0}{1}", items[i], separator);
}
}

我的方法在每次迭代时使用 new 创建三个引用变量。我正在努力优化这段代码,并计划按如下方式实现该方法

protected List<string> WrapInTwoLines(string[] originalLines, int lineLimit, List<string> wrappedLines, StringBuilder actualLine)
{
///There will be always two lines even first line can be empty and whole data goes to 2nd line
//string[] originalLines = text.Split(new string[] { " " }, StringSplitOptions.None);

//List<string> wrappedLines = new List<string>();
wrappedLines.Clear();

//StringBuilder actualLine = new StringBuilder();
actualLine.Clear();
//Rest remains the same
}

我认为它会改进代码,但我不确定它会改进多少或是否会改进代码。我可以使用哪些工具/技术来比较内存或速度方面的代码优化?另一个问题是,这是将方法变量作为参数传递的好模式(如上述方法 actualLine 等)吗?

最佳答案

此更改不会显着提高性能。 Java 和 C# 的垃圾收集器经过优化,可以很好地收集小的短期对象,如 wrappedLines 和 actualLine。当您清除 wrappedLines 而不是创建新的 wrappedLines 时,GC 仍然必须收集 wrappedLines 中包含的所有字符串。

除非您遇到性能问题,否则不要通过猜测性能优化来使您的代码复杂化。如果没有额外的参数,WrapInTwoLines 方法更容易理解并且更不容易出错。

如果您遇到性能问题,请先查看最内层的循环 - 这是最常执行的代码。 AppendFormat 需要格式字符串的运行时解析 - 这将比 Append("").Append(originalLines[i]).

就工具而言,我只多次运行问题代码并对其计时就获得了最好的结果。有更复杂的工具可用,但我没有发现它们有多大值(value)。始终运行多个计时试验并对其进行平均,因为单个试验可能会出现偏差。

关于c# - 将方法变量作为参数传递以进行代码优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22626814/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com