StringBuilder的效率高么?

时间:2022-04-24 19:57:24

import lint;
import System;
import System.Text;
var data = {
        products : [ { name: "mac", desc: "computer",    
                       price: 1000, quantity: 100, alert:null },
                     { name: "ipod", desc: "music player",
                       price:  200, quantity: 200, alert:"on sale now!" },
                     { name: "cinema display", desc: "screen",      
                       price:  800, quantity: 300, alert:"best deal!" } ],
        customer : { first: "John", last: "Public", level: "gold" }
    };
var cart_jst=
    "Hello ${customer.first} ${customer.last}.<br/>/
    Your shopping cart has ${products.length} item(s):/
    <table>/
     <tr><td>Name</td><td>Description</td>/
         <td>Price</td><td>Quantity & Alert</td></tr>/
     {for p in products}/
         <tr><td>${p.name|capitalize}</td><td>${p.desc}</td>/
             <td>$${p.price}</td><td>${p.quantity} : ${p.alert|default:/"/"|capitalize}</td>/
             </tr>/
     {forelse}/
         <tr><td colspan=/"4/">No products in your cart.</tr>/
     {/for}/
    </table>/
    {if customer.level == /"gold/"}/
      We love you!  Please check out our Gold Customer specials!/
    {else}/
      Become a Gold Customer by buying more stuff here./
    {/if}"
var str=new StringBuilder();   
var str2=[];
var str3;
var d1,d2 = DateTime.Now;


for(var i=0;i<1000;i++)
    str.Append(cart_jst);
var d1 = DateTime.Now;
str3=str.ToString();
Console.WriteLine(d1-d2);
var myTemplateObj = lint.Tpl.parseTemplate(str3).process(data);
d2 = DateTime.Now;


Console.WriteLine(d2-d1);

for(var i=0;i<1000;i++)
    str2[i]=cart_jst
str3=    str2.join();
d1 = DateTime.Now;

Console.WriteLine(d1-d2);
var myTemplateObj = lint.Tpl.parseTemplate(str3).process(data);
d2 = DateTime.Now;

Console.WriteLine(d2-d1);

为了看卡模板的处理能力,我把数据量做了提升,顺便用两种方法来测试大字符串的效率

一种用微软主推的StringBuilder

一种我习惯的字符串数组,发现数组效率比上种高多了。

但是如果数组采用自增量

    str2[str2.length]=cart_jst

效率和stringBuilder差不多