簡體   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