繁体   English   中英

在 C#/ASP.NET 中渲染 html 的最有效方法

[英]The most efficient method to render html in C#/ASP.NET

我们必须在 C# 中实现一些 html 渲染,我们正在寻找有效的方法来做到这一点。

这是我们要渲染的 html:

<h1> Title {34}</h1>
<p>Paragraph  {4}</p>
<div> Div here {14}</div>

数字 {34}、{4}、{14} 必须替换为字典中的值。

我们正在寻找高效的查找、提取数字和替换。 html 动态和数字也是。

一种解决方案是使用正则表达式,但我们有更好的选择吗?

我的理解是您有一个从其他地方获取的静态 html 文件,并且您想用dict[x]替换模式{x} ,其中 x 是一个数字和一个字典值的键。 这可以使用正则表达式来完成,无论是使用 C#(或其他任何东西)的服务器端还是使用 Javascript 的客户端。 这是一个示例js解决方案:

 const oldHTML = "<h1>Title {34}</h1><p>Paragraph {4}</p><div> Div here {14}</div>" document.querySelector('#before').innerHTML = oldHTML; const dict = { "4": "dict value for 4", "14": "dict value for 14", "34": "dict value for 34" }; const newHTML = oldHTML.replace(/\\{[0-9]+\\}/g, (str) => { const num = str.slice(1, str.length - 1); return dict[num]; }); document.querySelector('#after').innerHTML = newHTML;
 <div id="before"></div> <div id="after"></div>

我不知道您所说的“高效”究竟是什么意思,但这应该可以解决问题。 如果您不想在客户端完成,请在您的服务器上使用类似的解决方案。 这实际上取决于此“字典”的存储位置以及您打算如何从中获取值。

我会给你一个解决方案,它不仅比 split 快,而且内存效率高,适合流操作。

这是 c# 代码(我将您的解决方案与我的解决方案放在一起,以便我们可以比较运行时间):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace htmlRender
{
    class Program
    {
        const string oldHTML = "<h1>Title {34}</h1><p>Paragraph {4}</p><div> Div here {14}</div>";
        static Dictionary<string, string> dict = new Dictionary<string, string>()
            {
                {  "4", "dict value for 4" },
                { "14", "dict value for 14"},
                { "34", "dict value for 34"}
            };

        static void Main(string[] args)
        {
            Stopwatch sw = Stopwatch.StartNew();
            Regex rx = new Regex(@"{\d+}");

            string newHTMLRegex = rx.Replace(oldHTML, new MatchEvaluator(ReplaceText));
            sw.Stop();
            //Console.WriteLine(newHTMLRegex);
            Console.WriteLine("Execution time regex took " + sw.ElapsedTicks + " ticks.");

            sw = Stopwatch.StartNew();
            var sb = new StringBuilder();
            var str = oldHTML.Split(new char[] { '{', '}' });
            if (str.Length > 0)
            {
                for (int i = 0; i < str.Length; i += 2)
                {
                    sb.Append(str[i]);
                    if (str.Length > i + 1)
                        sb.Append(dict[str[i + 1]]);
                }
            }
            string newHTMLSplit = sb.ToString();
            sw.Stop();
            //Console.WriteLine(newHTMLSplit);
            Console.WriteLine("Execution time split took " + sw.ElapsedTicks + " ticks.");


            sw = Stopwatch.StartNew();
            var charBuffer = new char[10];
            int buffered = 0;
            bool buffering = false;
            var writer = new StringBuilder();
            for (int i = 0; i < oldHTML.Length; i++)
            {
                if (!buffering && oldHTML[i] == '{')
                {
                    buffering = true;
                }
                else if (buffering)
                {
                    if (oldHTML[i] == '}')
                    {
                        writer.Append(dict[new string(charBuffer, 0, buffered)]);
                        buffered = 0;
                        buffering = false;
                    }
                    else if (oldHTML[i] == '0' ||
                            oldHTML[i] == '1' ||
                            oldHTML[i] == '2' ||
                            oldHTML[i] == '3' ||
                            oldHTML[i] == '4' ||
                            oldHTML[i] == '5' ||
                            oldHTML[i] == '6' ||
                            oldHTML[i] == '7' ||
                            oldHTML[i] == '8' ||
                            oldHTML[i] == '9')
                    {
                        charBuffer[buffered] = oldHTML[i];
                        buffered += 1;
                    }
                    else
                    {
                        writer.Append(new string(charBuffer, 0, buffered));
                        buffered = 0;
                        buffering = false;
                    }
                }
                else
                {
                    writer.Append(oldHTML[i]);
                }
            }

            string newHTMLStream = writer.ToString();
            sw.Stop();
            Console.WriteLine(newHTMLStream);
            Console.WriteLine("Execution time stream took " + sw.ElapsedTicks + " ticks.");

            Console.ReadKey();
        }

        static string ReplaceText(Match m)
        {
            string x = m.ToString().Replace("{", "").Replace("}", "");

            return dict[x];
        }
    }
}

我的一次运行的执行时间是:

Execution time regex took 17814 ticks.
Execution time split took 100 ticks.
Execution time stream took 51 ticks.

最好的问候,贝蒂姆贝贾。

我做了一些研究,发现了一些我想分享的东西。 请注意,呈现的 html 是包含{num}的特殊格式

这是 C# 中的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace htmlRender
{
    class Program
    {
        const string oldHTML = "<h1>Title {34}</h1><p>Paragraph {4}</p><div> Div here {14}</div>";
        static Dictionary<string, string> dict = new Dictionary<string, string>()
            {
                {  "4", "dict value for 4" },
                { "14", "dict value for 14"},
                { "34", "dict value for 34"}
            };

        static void Main(string[] args)
        {
            Stopwatch sw = Stopwatch.StartNew();
            Regex rx = new Regex(@"{\d+}");

            string newHTMLRegex = rx.Replace(oldHTML, new MatchEvaluator(ReplaceText));
            sw.Stop();
            //Console.WriteLine(newHTMLRegex);
            Console.WriteLine("Execution time regex took " + sw.ElapsedTicks + " ticks.");


            sw = Stopwatch.StartNew();
            var sb = new StringBuilder();
            var str = oldHTML.Split(new char[] { '{', '}' });
            if (str.Length > 0)
            {
                for (int i = 0; i < str.Length; i += 2)
                {
                    sb.Append(str[i]);
                    if (str.Length > i + 1)
                        sb.Append(dict[str[i + 1]]);
                }
            }
            string newHTMLSplit = sb.ToString();
            sw.Stop();
            //Console.WriteLine(newHTMLSplit);
            Console.WriteLine("Execution time split took " + sw.ElapsedTicks + " ticks.");

            Console.ReadKey();
        }

        static string ReplaceText(Match m)
        {
            string x = m.ToString().Replace("{", "").Replace("}", "");

            return dict[x];
        }
    }
}

这是我的执行,有显着改进

Execution time regex took 6894 ticks.
Execution time split took 65 ticks.

以下是@irakslis回答后的 JavaScript 版本:

 const oldHTML = "<h1>Title {34}</h1><p>Paragraph {4}</p><div> Div here {14}</div>"; document.querySelector('#oldHTML').innerHTML = oldHTML; const dict = { "4": "dict value for 4", "14": "dict value for 14", "34": "dict value for 34" }; let start = performance.now(); let newHTML = oldHTML.replace(/\\{[0-9]+\\}/g, (str) => { const num = str.slice(1, str.length - 1); return dict[num]; }); var end = performance.now(); console.log("Execution time regex took " + (end - start) + " milliseconds."); document.querySelector('#newHtmlRegex').innerHTML = newHTML; start = performance.now(); let sb = []; var str = oldHTML.split(/{|}/); if (str.length > 0) { for (var i = 0; i < str.length; i += 2) { sb.push(str[i]); if (str.length > i + 1) sb.push(dict[str[i + 1]]); } } newHTML = sb.join(''); end = performance.now(); console.log("Execution time split took " + (end - start) + " milliseconds."); document.querySelector('#newHtmlSplit').innerHTML = newHTML;
 <div id="oldHTML"></div> <div id="newHtmlRegex"></div> <div id="newHtmlSplit"></div>

使用 split 而不是正则表达式,html 实现性能提高了 30-70%。

Execution time regex took 0.1550000160932541 milliseconds.
Execution time split took 0.044999876990914345 milliseconds.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM