Pages

2014년 11월 4일 화요일

[JAVASCRIPT] 문자열 Byte 길이 구하기

아래 방식에서 "개선된 FOR문으로 문자열 BYTE 계산" 방식이 가장 빠르게 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* 변수선언 */
var string = undefined; //테스트할 문자열
   
/* 문자열 초기화 */
for(var j=0; j<10000; j++)
    string += "This is 아무의미없는 문자열";
var stringLength = string.length;
var stringByteLength = 0;
   
   
/* 일반적인 FOR문으로 문자열 BYTE 계산 */
console.time("일반적인FOR방식"); 
for(var i=0; i<stringLength; i++)
{
    if(escape(string.charAt(i)).length >= 4)
        stringByteLength += 3;
    else if(escape(string.charAt(i)) == "%A7")
        stringByteLength += 3;
    else
        if(escape(string.charAt(i)) != "%0D")
            stringByteLength++;
}
console.log(stringByteLength + " Bytes")
console.timeEnd("일반적인FOR방식");
   
   
/* 개선된 FOR문으로 문자열 BYTE 계산 */
console.time("개선된FOR방식");
stringByteLength = (function(s,b,i,c){
    for(b=i=0;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
    return b
})(string);
console.log(stringByteLength + " Bytes");
console.timeEnd("개선된FOR방식");
   
   
/* encodeURI로 문자열 BYTE 계산 */
console.time("encodeURI방식");
stringByteLength = ~-encodeURI(string).split(/%..|./).length;
console.log(stringByteLength + " Bytes");
console.timeEnd("encodeURI방식");
   
   
/* 정규식을 활용한 계산 */
console.time("정규식방식");
stringByteLength = string.replace(/[\0-\x7f]|([0-\u07ff]|(.))/g,"$&$1$2").length;
console.log(stringByteLength + " Bytes");
console.timeEnd("정규식방식");


댓글 없음:

댓글 쓰기