JavaScript optimization: BASE64 quick Edition

Source: Internet
Author: User

  Tutorial on helping customers (www.bkjia.com)The BASE64 principle is very simple, but to write an efficient script, especially the highly flexible and low-efficiency script such as JS, you still need to consider it.

Let's take a look at the popular online versions. Declare 64 constant characters first:

Reference content is as follows:
Var key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 +/= ";

This step is the same and there is no better way to list these characters. However, the next practice will be very exquisite. Because the key here is a String, many versions are filled with charAt and even indexOf functions to operate on this key. CharAt is used to access the nth character of the key, which is still being cleared; but indexOf is used to determine the character position, which cannot be forgiven. VBScript can be used in combination, but in JS, this method is very bad and obviously it is not flexible. What is flexibility? In the shortest case, hash tables are used. Hash Tables are inherent in JS, and their efficiency is incomparable to other methods. It is clear that in algorithms such as BASE64 that frequently convert numbers and characters, hash is a must.

Let's talk about charAt. Although charAt is not as efficient as indexOf, it is not the best. There are two types of script programs. One is self-written, and the other is the built-in system in the browser, which is called [Native Code]. The efficiency of the latter is, of course, much higher than that of the former. So as much code as possible can be handed over to the system for execution. Sometimes it may seem that the calculation workload has increased, but the final speed has actually increased.

For BASE64 decoding, the parameter is a String. The conventional method is to charAt each character first. If there are 10 thousand characters, charAt runs 10 thousand times. Can I Merge multiple charAt functions into one local code call? Of course:

Var arr = str. split ('');

Then str. charAt (I) can be replaced by arr [I. Although this method opens up more memory, the final efficiency is improved and the code readability is enhanced. Of course, Chrome is no different in browsers that run extremely fast, such as FireFox, and may even go backwards.

Finally, there is a hierarchical problem. People on the Internet often say how BASE64 supports Chinese. According to this statement, BASE64 is used to encode and decode the string, which is somewhat different from its meaning. BASE64 is initially used to convert a binary file to a visible character and send it in an email. So its significance lies in the conversion of binary and character, rather than the conversion of character and character. JS does not have binary data, but it can be simulated using an array ranging from 0 to 25. Therefore:

Function encoding function (Array []) {return String ;}

Function decoding function (String) {return Array [];}

As for Chinese, Unicode and ANSI conversion is nothing more. JS does not seem to have ready-made conversion functions. To implement this function, you can use Unicode and ANSI tables. However, both parties use Unicode for encoding/decoding.

The Unsupported support does not exist.

Final code:

Reference content is as follows:
<Script>
Var mapEn = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 +/". split ('');
Var mapDe = {};

For (var I = 0; I <64; I ++)
MapDe [mapEn [I] = I;

/*
* Function: Base64Encode
* Description: Encoding
* Tutorial: bkjia.com
*/
Function Base64Encode (data)
{
Var buf = [];
Var map = mapEn;
Var n = data. length; // The total number of bytes.
Var val; // median value
Var I = 0;

/*
* 3 bytes ==> val ==> 4 characters
*/
While (I <n)
{
Val = (data [I] <16) |
(Data [I + 1] <8) |
(Data [I + 2]);

Buf. push (map [val> 18],
Map [val> 12 & 63],
Map [val> 6 & 63],
Map [val & 63]);
I + = 3;
}

If (n % 3 = 1) // combine two "="
Buf. pop (), buf. pop (), buf. push ('=', '= ');
Else // assemble a "="
Buf. pop (), buf. push ('= ');

Return buf. join ('');
}

/*
* Function: Base64Decode
* Description: Decoding
*/
Function Base64Decode (str)
{
Var buf = [];
Var arr = str. split ('');
Var map = mapDe;
Var n = arr. length; // The total number of characters.
Var val; // median value
Var I = 0;

/*
* Length exception
*/
If (n % 4)
Return;

/*
* 4 characters ==> val ==> 3 bytes
*/
While (I <n)
{
Val = (map [arr [I] <18) |
(Map [arr [I + 1] <12) |
(Map [arr [I + 2] <6) |
(Map [arr [I + 3]);

Buf. push (val> 16,
Val> 8 & 0xFF,
Val & 0xFF );
I + = 4;
}

/*
* Number of character "="
*/
While (arr [-- n] = ')
Buf. pop ();

Return buf;
}
</Script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.