gpt4 book ai didi

c# - 使用 C# 哪个更快 - System.Convert.ToString( objThatIsString) 或 (string)objThatIsString?

转载 作者:太空狗 更新时间:2023-10-29 23:53:53 28 4
gpt4 key购买 nike

或 objThatIsString.ToString() 正如在回答中指出的那样 ..更快而不是更聪明..

最佳答案

@thijs:这是一个快速测试:

public class ToStringTest
{
private object mString = "hello world!";
Stopwatch sw = new Stopwatch();
private List<long> ConvertToStringTimes = new List<long>();
private List<long> ToStringTimes = new List<long>();
private List<long> CastToStringTimes = new List<long>();

public ToStringTest()
{

for (int i = 0; i < 100000; i++)
{
sw.Start();
ConvertToString();
sw.Stop();
ConvertToStringTimes.Add(sw.ElapsedTicks);
sw.Reset();

sw.Start();
ToString();
sw.Stop();
ToStringTimes.Add(sw.ElapsedTicks);
sw.Reset();

sw.Start();
CastToString();
sw.Stop();
CastToStringTimes.Add(sw.ElapsedTicks);
sw.Reset();
}
Console.WriteLine("Average elapsed ticks after converting {0} strings",ConvertToStringTimes.Count);
Console.WriteLine("ConvertToString: {0} ticks", ConvertToStringTimes.Average() );
Console.WriteLine("ToString: {0} ticks", ToStringTimes.Average());
Console.WriteLine("CastToString: {0} ticks", CastToStringTimes.Average());
}

private string ConvertToString()
{
return Convert.ToString(mString);
}

public override string ToString()
{
return mString.ToString();
}

public string CastToString()
{
return (string) mString;
}
}

结果:

转换 100000 个字符串后的平均耗时

ConvertToString:611.97372 个刻度

ToString:586.51461 个滴答声

CastToString:582.25266 刻

关于c# - 使用 C# 哪个更快 - System.Convert.ToString( objThatIsString) 或 (string)objThatIsString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/909951/

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