什么是提取在C#中的字符串中的5位数字的最快方法 [英] what's the quickest way to extract a 5 digit number from a string in c#

查看:282
本文介绍了什么是提取在C#中的字符串中的5位数字的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是从C#中的字符串中提取一个5位数的最快方式。

what's the quickest way to extract a 5 digit number from a string in c#.

我有

string.Join(null, System.Text.RegularExpressions.Regex.Split(expression, "[^\\d]"));



任何其他方面?

Any others?

推荐答案

正则表达式的方法可能是最快的实现,但不是最快的运行。我比较了一个简单的正则表达式解决以下手动搜索代码,并发现手动搜索代码是〜2倍,2.5倍更快较大的输入字符串和快4倍的小弦:

The regex approach is probably the quickest to implement but not the quickest to run. I compared a simple regex solution to the following manual search code and found that the manual search code is ~2x-2.5x faster for large input strings and up to 4x faster for small strings:

static string Search(string expression)
{
  int run = 0;
  for (int i = 0; i < expression.Length; i++)
  {
    char c = expression[i];
    if (Char.IsDigit(c))
      run++;
    else if (run == 5)
      return expression.Substring(i - run, run);
    else
      run = 0;
  }
  return null;
}
const string pattern = @"\d{5}";
static string NotCached(string expression)
{
  return Regex.Match(expression, pattern, RegexOptions.Compiled).Value;
}

static Regex regex = new Regex(pattern, RegexOptions.Compiled);
static string Cached(string expression)
{
  return regex.Match(expression).Value;
}



结果一〜50字符字符串中的一个5位数字串中间,超过10 ^ 6次迭代,以微秒每次通话的等待时间(较少数量的更快):

Results for a ~50-char string with a 5-digit string in the middle, over 10^6 iterations, latency per call in microseconds (smaller number is faster):

简单搜索:0.648396us

Simple search: 0.648396us

缓存正则表达式:2.1414645us

Cached Regex: 2.1414645us

非缓存正则表达式:3.070116us

Non-cached Regex: 3.070116us

结果一〜40K字符串中间超过10 ^ 4次迭代一个5位数的字符串,每次通话延迟以微秒(较小的数字是更快):

Results for a ~40K string with a 5-digit string in the middle over 10^4 iterations, latency per call in microseconds (smaller number is faster):

简单搜索:423.801us

Simple search: 423.801us

缓存正则表达式:1155.3948us

Cached Regex: 1155.3948us

非缓存正则表达式:1220.625us

Non-cached Regex: 1220.625us

一个令人感到有点惊讶。我本来期望正则表达式 - 这是编译为IL - 成为媲美手动搜索,至少对于非常大的字符串

A little surprising: I would have expected Regex -- which is compiled to IL -- to be comparable to the manual search, at least for very large strings.

这篇关于什么是提取在C#中的字符串中的5位数字的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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