Just another high performance string format function for Javascript

Source: Internet
Author: User
// Copyright (c) He Shi-jun <Hax. SFO at gmail dot com>, 2006
// Below codes can be used under GPL (V2 or later) or lgpl (V2.1 or later) License

Format2.cache = ...{};
Function format2 (pattern )...{
If (! (Pattern in format2.cache ))...{
Format2.cache [pattern] = new function ('"' + pattern. replace (/"/g ,'/"'). replace (/$ ([0-9] +)/g, '"+ arguments [$1] + "'). replace (/$/g, '$') + '"');
}
Return format2.cache [pattern] (arguments );
}

 

Compare to previous method, it's even more fast in heavy using (especially on Firefox and opera), because it's compile the pattern to function and cache it. but this method will waste memory. so the best practice is combining these two methods.

And the no Cache version here, but not helpful, because it's lose the advantage of cacheable and will be very slow on opera:

// Copyright (c) He Shi-jun <Hax. SFO at gmail dot com>, 2006
// Below codes can be used under GPL (V2 or later) or lgpl (V2.1 or later) License

Function format3 (pattern )...{
Return eval ('"' + pattern. replace (/"/g ,'/"'). replace (/$ ([0-9] +)/g, '"+ arguments [$1] + "'). replace (/$/g, '$') + '"');
}

 

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.