A high performance string format function for JavaScript

原创 2006年11月27日 13:57:00
2006-11-30 Updated: I also write another high performance string format function which compiles the pattern into function and cache it for reuse.


Last month, I wrote a logging tool for js, and to avoid performance depression, I need a string formatter function.
I found that though many js toolkit or framework provide string format function, such as Atlas, but they r not quite fast. Most r using String.replace(regex, func) to replace the placeholder(such as '{n}' or '$n'), but this function tend to slow, because every match will call the func, and js function calling is very expensive.
On the contrary, native functions r very fast, so to improve performance, we should utilize the native functions as possible as we can. A wonderful example is StringBuilder which use Array.join to concat the string.

So I create my String.format(), it's very fast.

Usage:

var name = 'world';
var result = 'Hello $1!'.format(name);
// result = "Hello world!"

var letters = String.format('$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', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
// letters = "abcdefghijklmnopqrstuvwxyz"

The later one almost same fast as the former one, no other implementation can have the same performance as I know.

Note:
1. It's depend on String.replace(regex, string), so u can use at most 99 placeholder($1 to $99), but if the script engine is too old, it maybe only support nine ($1 to $9) or not work at all (eg. JScript before 5.5?).
2. literal $ should be escape into $$ (two $).
3. $` and $' will be reomoved, and $& will replaced into some strange things :)
4. There is a magic character which you can't use anyway, currently I choose 0x1f (which means data separator in ascii and unicode).

2006-11-30 Updated:
'$1 1'.format('a') result in 'a 1', if you want to strip the space, u can't write '$11'.format(...) because it will try to match the 11nd parameter, u should write '$011'.format(...) instead.

Source code:

// 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

    if (!String._FORMAT_SEPARATOR) ...{
        String._FORMAT_SEPARATOR 
= String.fromCharCode(0x1f);
        String._FORMAT_ARGS_PATTERN 
= new RegExp('^[^' + String._FORMAT_SEPARATOR + ']*'
            
+ new Array(100).join('(?:.([^' + String._FORMAT_SEPARATOR + ']*))?'));
    }

    
if (!String.format)
    String.format 
= function (s) ...{
        
return Array.prototype.join.call(arguments, String._FORMAT_SEPARATOR).
            replace(String._FORMAT_ARGS_PATTERN, s);
    }

    
if (!''.format)
    String.prototype.format 
= function () ...{
        
return (String._FORMAT_SEPARATOR +
            Array.prototype.join.call(arguments, String._FORMAT_SEPARATOR)).
            replace(String._FORMAT_ARGS_PATTERN, 
this);
    }

    

深度学习论文理解3:Flexible, high performance convolutional neural networks for image classification

本文是11年Dan C.Ciresan的作品,主要贡献是提供了一种快速,全GPU部署的CNN计算框架,通过快速的GPU计算可以让作者尝试相对以前的神经网络更深的CNN,而且是仅仅使用监督学习的方式。 ...

A High-Performance Nehalem iDataPlex Cluster and DDN S2A9990 Storage for Texas A&M University

本文转载自:http://sc.tamu.edu/systems/eos/

Using JAX-RS with Protocol Buffers for high-performance REST APIs

Posted on December 27, 2008 by Sam Pullara One of the great things about the JAX-RS specificati...
  • xeseo
  • xeseo
  • 2013年10月17日 10:17
  • 1608

ArrayFire:高性能并行计算软件库 ArrayFire: a high performance software library for parallel computing

About ArrayFire ArrayFire is a high performance software library for parallel computing with an e...

BigPipe: Pipelining web pages for high performance

BigPipe: Pipelining web pages for high performance 由 Changhao Jiang 于 2010年6月4日11:34 发布 ...

Patterns for Building High Performance Applications

http://java.sys-con.com/node/2116436 Performance is one word that is used to describe multiple ...
  • ukong
  • ukong
  • 2012年03月04日 23:07
  • 179

High Performance Canvas Game for Android(高性能Android Canvas游戏开发)

Rule #0 为移动平台进行优化 为移动平台进行优化是十分重要的,因为移动平台的性能大概只有桌面平台的1/10左右(*1),它通常意味着: 更慢的CPU速度,这意味着不经过优化的Java...
  • rogeryi
  • rogeryi
  • 2013年08月31日 18:13
  • 5337

TreeFTL:Efficient RAM Management for High Performance of NAND Flash-based Storage Systems-论文注释笔记

不是翻译机器,所以不会去完全翻译,但除了废话基本等于完全翻译了。。。 方便快速浏览和看懂,不保证完美,不过大概都理解,有需要可以讨论。 因为是PDF上直接做的手脚,加上插图,没法发博客,所以选择整个...

Tuning options for SQL Server when running in high performance workloads

原文链接:https://support.microsoft.com/en-us/kb/920093Contents This article describes various trace flag...

<<High Performance JavaScript>>读书笔记-2.Data Access

Scope Chains and Identifier Resolution function add(num1, num2){ var sum = num1 + num2; ret...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:A high performance string format function for JavaScript
举报原因:
原因补充:

(最多只允许输入30个字)