IT

JavaScript에는 stringbuilder 클래스가 내장되어 있습니까?

lottoking 2020. 5. 31. 10:33
반응형

JavaScript에는 stringbuilder 클래스가 내장되어 있습니까?


내가 볼 몇 가지 코드 프로젝트 솔루션을 .

그러나 JavaScript에서 정기적으로 구현됩니까?


Internet Explorer 용 코드를 작성해야하는 경우 배열 조인을 사용하는 구현을 선택했는지 확인하십시오. IE 에서 +또는 +=연산자로 문자열을 연결하면 속도가 매우 느립니다. IE6의 경우 특히 그렇습니다. 최신 브라우저 +=에서는 일반적으로 배열 조인만큼 빠릅니다.

많은 문자열 연결을 수행해야 할 때 일반적으로 배열을 채우고 문자열 빌더 클래스를 사용하지 않습니다.

var html = [];
html.push(
  "<html>",
  "<body>",
  "bla bla bla",
  "</body>",
  "</html>"
);
return html.join("");

push메소드는 여러 인수를 허용합니다.


방금 http://jsperf.com/javascript-concat-vs-join/2 에서 성능을 다시 확인했습니다 . 테스트 사례는 알파벳을 1,000 번 연결하거나 연결합니다.

현재 브라우저 (FF, Opera, IE11, Chrome)에서 "concat"은 "join"보다 약 4-10 배 빠릅니다.

IE8에서는 둘 다 동일한 결과를 반환합니다.

IE7에서 "join"은 불행히도 약 100 배 더 빠릅니다.


아니요, 문자열 작성에 대한 기본 지원은 없습니다. 대신 연결을 사용해야합니다.

물론 문자열의 다른 부분으로 구성된 배열을 만든 다음 join()해당 배열 을 호출 할 수 있지만 사용중인 JavaScript 인터프리터에서 조인이 구현되는 방식에 따라 다릅니다.

str1+str2방법 의 속도와 방법 의 속도를 비교하기 위해 실험을했습니다 array.push(str1, str2).join(). 코드는 간단했다 :

var iIterations =800000;
var d1 = (new Date()).valueOf();
str1 = "";
for (var i = 0; i<iIterations; i++)
    str1 = str1 + Math.random().toString();
var d2 = (new Date()).valueOf();
log("Time (strings): " + (d2-d1));

var d3 = (new Date()).valueOf();
arr1 = [];
for (var i = 0; i<iIterations; i++)
    arr1.push(Math.random().toString());
var str2 = arr1.join("");
var d4 = (new Date()).valueOf();
log("Time (arrays): " + (d4-d3));

Windows 7 x64에서 Internet Explorer 8 및 Firefox 3.5.5에서 테스트했습니다.

처음에는 적은 수의 반복 (약 수백, 수천 개의 항목)을 테스트했습니다. 결과는 예측할 수 없었습니다 (때때로 문자열 연결에는 0 밀리 초가 걸리고 때로는 16 밀리 초가 걸리며 어레이 결합에 동일 함).

카운트를 50,000으로 늘리면 브라우저마다 결과가 달라졌습니다 .Internet Explorer에서 문자열 연결이 더 빨라지고 (94 밀리 초) 조인이 느려졌으며 (125 밀리 초) 파이어 폭스에서는 배열 조인이보다 빠릅니다 (113 밀리 초) 문자열 결합 (117 밀리 초)

그런 다음 카운트를 500'000으로 늘 렸습니다. 지금은 array.join()했다 문자열 연결보다 느리게 두 브라우저에서 : 문자열 연결은 937 Internet Explorer에서 MS, 파이어 폭스에서 1155 MS, 배열 Internet Explorer에서 1265에 참가, 파이어 폭스에서 1207 MS이었다.

Internet Explorer에서 "스크립트를 실행하는 데 시간이 오래 걸립니다"없이 테스트 할 수있는 최대 반복 횟수는 850,000입니다. 그런 다음 Internet Explorer는 문자열 연결의 경우 1593, 배열 결합의 경우 2046이었고 Firefox는 문자열 연결의 경우 2101, 배열 결합의 경우 2249입니다.

결과 -반복 횟수가 적은 경우 array.join()Firefox에서 더 빠를 수 있으므로 사용을 시도 할 수 있습니다. 숫자가 증가하면 string1+string2방법이 더 빠릅니다.

최신 정보

Internet Explorer 6 (Windows XP)에서 테스트를 수행했습니다. 10 만회 이상 반복하여 테스트를 시도한 경우 프로세스가 즉시 응답하지 않고 종료되지 않았습니다. 40,000 회 반복에서 결과는

Time (strings): 59175 ms
Time (arrays): 220 ms

즉, Internet Explorer 6을 지원해야하는 array.join()경우 문자열 연결보다 빠른 방법을 선택하십시오 .


That code looks like the route you want to take with a few changes.

You'll want to change the append method to look like this. I've changed it to accept the number 0, and to make it return this so you can chain your appends.

StringBuilder.prototype.append = function (value) {
    if (value || value === 0) {
        this.strings.push(value);
    }
    return this;
}

The ECMAScript 6 version (aka ECMAScript 2015) of JavaScript introduced string literals.

var classType = "stringbuilder";
var q = `Does JavaScript have a built-in ${classType} class?`;

Notice that back-ticks, instead of single quotes, enclose the string.


In C# you can do something like

 String.Format("hello {0}, your age is {1}.",  "John",  29) 

In JavaScript you could do something like

 var x = "hello {0}, your age is {1}";
 x = x.replace(/\{0\}/g, "John");
 x = x.replace(/\{1\}/g, 29);

For those interested, here's an alternative to invoking Array.join:

var arrayOfStrings = ['foo', 'bar'];
var result = String.concat.apply(null, arrayOfStrings);
console.log(result);

The output, as expected, is the string 'foobar'. In Firefox, this approach outperforms Array.join but is outperformed by + concatenation. Since String.concat requires each segment to be specified as a separate argument, the caller is limited by any argument count limit imposed by the executing JavaScript engine. Take a look at the documentation of Function.prototype.apply() for more information.


When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com


How about sys.StringBuilder() try the following article.

https://msdn.microsoft.com/en-us/library/bb310852.aspx


I have defined this function:

function format() {
        var args = arguments;
        if (args.length <= 1) { 
            return args;
        }
        var result = args[0];
        for (var i = 1; i < args.length; i++) {
            result = result.replace(new RegExp("\\{" + (i - 1) + "\\}", "g"), args[i]);
        }
        return result;
    }

And can be called like c#:

 var text = format("hello {0}, your age is {1}.",  "John",  29);

Result:

hello John, your age is 29.

참고URL : https://stackoverflow.com/questions/2087522/does-javascript-have-a-built-in-stringbuilder-class

반응형