本文基于StackOverflow的以下问题收集整理而成。
What is the fastest waty to count newlines in a large .NET string: http://stackoverflow.com/questions/2557002/what-is-the-fastest-way-to-count-newlines-in-a-large-net-string
How to count lines in a string: http://stackoverflow.com/questions/11189331/how-to-count-lines-in-a-string

方法一

private static int Count1(string s)
{
int len = s.Length;
int c = 0;
for (int i=0; i < len; i++)
{
if (s[i] == '\n') c++;
}
return c+1;
}

方法二

private static int Count2(string s)
{
int count = -1;
int index = -1; do
{
count++;
index = s.IndexOf('\n', index + 1);
}
while (index != -1); return count+1;
}

方法三

private static int Count3(string s)
{
return s.Count( c => c == '\n' ) + 1;
}

方法四

private static int Count4(string s)
{
int n = 0;
foreach( var c in s )
{
if ( c == '\n' ) n++;
}
return n+1;
}

方法五

private static int Count5(string s)
{
var a = s.ToCharArray();
int c = 0;
for (int i=0; i < a.Length; i++)
{
if (a[i]=='\n') c++;
}
return c+1;
}

性能测试结果显示,最快到最慢为:方法四,方法二,方法一,方法五和方法二。方法二不仅最慢,而且差了1个数量级。

方法六

int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;

方法七

int numLines = aDiff.text.Split('\n').Length;

是为之记。
Alva Chien
2016.9.5

最新文章

  1. [No00008B]远程桌面发送“Ctrl+Alt+Delete”组合键调用任务管理器
  2. Redis 配置文件
  3. 推荐几个好用的在线svn空间
  4. webstorm调试Node的时候配置
  5. 如何启用Service,如何停用Service
  6. wxPython学习笔记(初识)
  7. canvas在手机qq浏览器显示错乱
  8. PHP设计模式之委托模式
  9. 负载均衡软件LVS分析四(测试)
  10. OC中成员属性 成员变量
  11. 漫谈android系统(4)bring up panel
  12. 在Windows Server 2008 R2下搭建jsp环境(四)-在测试的过程中可能出现的问题
  13. 制作docker-jdk7-zookeeper镜像(非集群版)
  14. SaltStack 安装、简单配置和远程执行
  15. Java设计模式之十一 ---- 策略模式和模板方法模式
  16. Luogu4622 COCI2012-2013#6 JEDAN 组合、DP
  17. 对spring cloud config的一点理解
  18. 转:cookie.setPath()用法
  19. Spring MVC和Spring Data JPA之按条件查询和分页(kkpaper分页组件)
  20. QQ消息无限发送!源代码

热门文章

  1. Java描述设计模式(15):责任链模式
  2. Powershell基础之脚本执行
  3. css 动画animation基本属性(干货)
  4. LeetCode初级算法--树01:二叉树的最大深度
  5. java集合之ArrayList链表基础
  6. Eureka错误解决方法
  7. vue css 深度选择器
  8. linux+jenkins+github+python持续集成
  9. python问题:IndentationError:expected an indented block
  10. mac外接显示器 字体发虚解决方案