有这样的功能,它从ID列表中创建字符串 我尝试在50个线程中运行它,30秒后它挂起应用程序
public string genText(List<string> list)
{
string text = @"{""text"":""";
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text += "!" + " ";
else
text += "!" + @""", ";
}
text += @"""start"":[";
for (int i = 0, lim = -2; i < list.Count; i++)
{
lim += 2;
if (i < list.Count - 1)
text += @"""" + lim + @""",";
else
text += @"""" + lim + @"""], ";
}
text += @"""end"":[";
for (int i = 1, lim = -1; i < list.Count + 1; i++)
{
lim += 2;
if (i < list.Count)
text += @"""" + lim + @""",";
else
text += @"""" + lim + @"""], ";
}
text += @"""type"":[";
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text += @"""USER"",";
else
text += @"""USER""], ";
}
text += @"""objectId"":[";
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text += @"""" + list[i] + @""",";
else
text += @"""" + list[i] + @"""]}";
}
return text;
}
编写此类函数的最佳(替代)方式是什么?
预期结果:{"text":"! ! ! ! ! ! ! ! ! ! ! ! ! ! !", "start":["0","2","4","6","8","10","12","14","16","18","20","22","24","26","28"], "end":["1","3","5","7","9","11","13","15","17","19","21","23","25","27","29"], "type":["USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER"], "objectId":["524231066205","363249609235","509321690322","551832845250","273337925148","553378679618","552270073142","256641407","545454406232","548096729194","555315805314","553271555117","573655339037","518779453704","486606264340"]}
答案 0 :(得分:0)
不使用串联字符串,而是使用StringBuilder类更有效。
public string genText(List<string> list)
{
StringBuilder text = new StringBuilder();
text.Append(@"{""text"":""");
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text.Append("!" + " ");
...
return text.ToString();
}
但正如其他人在评论中提到的那样,如果你想创建Json数据,请使用Json库。