【Unity】string的'+'与StringBuilder.Append的对比

using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

public class StringTest : MonoBehaviour
{
   int length;
    void Update()
    {
        //使用StringBuilder
            StringBuilder str = new StringBuilder("");
            for (int i = 0; i < length; i++)
            {
                str.Append(i);
            }
       //使用‘+’或string.Concat(string,string)
            string str = "";
            for (int i = 0; i < length; i++)
            {
                str += i;
               // string.Concat(str, i);
            }
      //使用string.Concat(string[])
          string[] str = new string[length];
          for (int i = 0; i < length; i++)
          {
              str[i] = i.ToString();
          }
         string result= String.Concat(str);
    }
}

length为10W的StringBuilder
这里写图片描述
length为1W的string‘+’
这里写图片描述
length为10W的string.Concat(string,string)
这里写图片描述
length为10W的string.Concat(string[])
这里写图片描述

可以看出,在长度确定的情况下,使用string.Concat(string[])效率最高
在length为10W的时候String.Concat(string,string)和StringBuilder效率相似
但当length为100W时
String.Concat(string.string)效率略低于string.Concat(string[]),StringBuilder效率最低,但三者差别都不大
这三者的效率更length为1W时的‘+’效率相似,所以‘+’跟其他的效率大概差100倍

public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception { URL url = new URL(hostUrl); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); String date = format.format(new Date()); //String date = format.format(new Date()); //System.err.println(date); StringBuilder builder = new StringBuilder("host: ").append(url.getHost()).append("\n").// append("date: ").append(date).append("\n").// append("GET ").append(url.getPath()).append(" HTTP/1.1"); //System.err.println(builder); Charset charset = Charset.forName("UTF-8"); Mac mac = Mac.getInstance("hmacsha256"); SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(charset), "hmacsha256"); mac.init(spec); byte[] hexDigits = mac.doFinal(builder.toString().getBytes(charset)); String sha = Base64.getEncoder().encodeToString(hexDigits); //System.err.println(sha); String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha); //System.err.println(authorization); HttpUrl httpUrl = HttpUrl.parse("https://" + url.getHost() + url.getPath()).newBuilder().// addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(charset))).// addQueryParameter("date", date).// addQueryParameter("host", url.getHost()).// build(); return httpUrl.toString(); } 将以上这段java转为UnityC#
最新发布
08-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值