字符串输出:在C#格式或CONCAT? [英] String output: format or concat in C#?

查看:177
本文介绍了字符串输出:在C#格式或CONCAT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说你要输出或CONCAT字符串。下列哪种风格你preFER?

Let's say that you want to output or concat strings. Which of the following styles do you prefer?


  • VAR P = {新名字=条例,姓氏=盖茨};

Console.WriteLine({0} {1},p.FirstName,p.LastName);

Console.WriteLine(p.FirstName ++ p.LastName);

你宁愿使用格式,或者你只是Concat的字符串?什么是你最喜欢的?正是这些伤害你的眼睛吗?

Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes?

你有任何理性的论据使用一个,而不是其他?

Do you have any rational arguments to use one and not the other?

我会去第二个。

推荐答案

试试这个code。

这是你的code略加修改的版本。

1.我删除Console.WriteLine这一它的幅度比我试图衡量慢大概很少订单。

2.我盯着循环之前秒表和右后停止它,这样一来,我没有失去precision如果函数有例如26.4蜱执行。

3.您可以通过迭代次数除以结果的方式是错误的。看看你是否有1000毫秒,100毫秒什么hapens。在这两种情况下,你会除以乘以1000000后得到0毫秒。

It's a slightly modified version of your code.
1. I removed Console.WriteLine as it's probably few orders of magnitude slower than what I'm trying to measure.
2. I'm staring the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute.
3. The way you divided result by number of iterations was wrong. See what hapens if you have 1000 milliseconds and 100 milliseconds. In both situations you will get 0 ms after dividing it by 1000000.

Stopwatch s = new Stopwatch();

var p = new { FirstName = "Bill", LastName = "Gates" };

int n = 1000000;
long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;

string result;
s.Start();
for (var i = 0; i < n; i++)
    result = (p.FirstName + " " + p.LastName);
s.Stop();
cElapsedMilliseconds = s.ElapsedMilliseconds;
cElapsedTicks = s.ElapsedTicks;
s.Reset();
s.Start();
for (var i = 0; i < n; i++)
    result = string.Format("{0} {1}", p.FirstName, p.LastName);
s.Stop();
fElapsedMilliseconds = s.ElapsedMilliseconds;
fElapsedTicks = s.ElapsedTicks;
s.Reset();


Console.Clear();
Console.WriteLine(n.ToString()+" x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");
Console.WriteLine(n.ToString() + " x result = (p.FirstName + \" \" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");
Thread.Sleep(4000);

以上是我的结果:

Those are my results:

百万x结果=的String.Format({0} {1},p.FirstName,p.LastName);花:618ms - 2213706蜱
  百万x结果=(p.FirstName ++ p.LastName);花:166ms - 595610蜱

1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 618ms - 2213706 ticks 1000000 x result = (p.FirstName + " " + p.LastName); took: 166ms - 595610 ticks

这篇关于字符串输出:在C#格式或CONCAT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆