「C#代码性能测试」循环创建坐标的最佳选择「建议收藏」

「C#代码性能测试」循环创建坐标的最佳选择「建议收藏」前言在开发过程中遇到了创建二维坐标的性能问题,分别使用Point类、元组、字符串三种方式测试在运行一亿次的情况下消耗时间的不同不同代码花费时间的

大家好,欢迎来到IT知识分享网。

前言

在开发过程中遇到了创建二维坐标的性能问题,分别使用Point类、元组、字符串三种方式测试在运行一亿次的情况下消耗时间的不同不同代码花费时间的长短,现将结果分享给大家。

提示:不同环境可能结果不同,仅供参考。

开发环境

  • Windows7
  • vscode2019

代码分享

第一种:通过Point类进行坐标创建(推荐)

C#代码:

//作者:好先生FX
var pointList = new List<Point>();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int x = 0; x < 10000; x++)
{
    for (int y = 0; y < 10000; y++)
    {
        var p = new Point(x, y);
        pointList.Add(p);
    }
}
stopwatch.Stop();
Debug.WriteLine("运行时间:" + stopwatch.ElapsedMilliseconds);

IT知识分享网

运行5次结果如下:

  1. 运行时间:1584
  2. 运行时间:1543
  3. 运行时间:1540
  4. 运行时间:1543
  5. 运行时间:1560

第二种:通过元组进行坐标创建

C#代码:

IT知识分享网var pointList = new List<Tuple<int, int>>();//作者:好先生FX
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int x = 0; x < 10000; x++)
{
    for (int y = 0; y < 10000; y++)
    {
        pointList.Add(new Tuple<int, int>(x, y));
    }
}
stopwatch.Stop();
Debug.WriteLine("运行时间:" + stopwatch.ElapsedMilliseconds);

运行5次结果如下:

  1. 运行时间:9998
  2. 运行时间:9907
  3. 运行时间:9814
  4. 运行时间:11509
  5. 运行时间:10547

第三种:通过字符串逗号分隔进行坐标创建

C#代码:

var pointList = new List<string>();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int x = 0; x < 10000; x++)
{
    for (int y = 0; y < 10000; y++)
    {
        pointList.Add(x + "," + y);
    }
}//作者:好先生FX
stopwatch.Stop();
Debug.WriteLine("运行时间:" + stopwatch.ElapsedMilliseconds);

运行5次结果如下:

  1. 运行时间:63049
  2. 运行时间:67412
  3. 运行时间:60787
  4. 运行时间:60811
  5. 运行时间:59766

结语

通过以上测试结果,推荐大家使用Point类进行二维坐标创建

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/6770.html

(0)
上一篇 2022-12-20 18:00
下一篇 2022-12-20 18:20

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信