nonCopyingString.js

Why we need it?

As i have learned before, IE s speed of String#slice and other substring methods depend from length of substring linearly. In other browser - const time. It means that IE do real copy, char by char, from string to substring, but other browsers just set two pointers as begin and end of substring in address space of string. I have tried to fix/optimize it.

Technology

Very easy. We just overwrite native String#slice which return our new NCString object with stored owner string and two pointers - begin and end if substring length >= copy threshold else return native substring. Also we do not forget to calculate length property. We use IEs DontEnum bug and store private properties in isPrototypeOf function object like this.isPrototypeOf.begin_. So you can only see isPrototypeOf and length as own properties of string. Technique of Object#valueOf and Object#toString allow us to return real substring on-demand in all javascript expressions(Object#valueOf calls)or brace operator and other operators, which calls Object#toString implicitly. Also all string native functions (like replace, match, ...) convert object to string by call toString. Extension object from String prototypically allow automatically get all current and future functions from String prototype (which automatic calls toString to convert object to string)

Addition features

We can make readonly functions like NCString#indexOf NCString#lastIndexOf NCString#charAt(two versions - for browsers which support '1'[0] == '1' or not) NCString#charCodeAt really fast and without getting real substring. With NCString#slice NCString#substring NCString#substr too.

Discovery

Firstly i tried to fully replace native String#slice. But as i discovered, copy threshold ~= 20500 chars. It s very big. It slowdown all algorithms which uses small strings. Because i decided to make separate String#_ncSlice for algorithms which uses really big strings. Also String#_ncSubstring and String#_ncSubstr.

ECMAScript5 compatibility

All custom String and NCString function fully compatible with ECMAScript5 lastest standard. There are some limitations which we can not fix. Object.prototype.toString.call(''._ncSlice(0)) != '[object String]' as for native string. Also typeof(''._ncSlice(0)) == 'object' instead 'string'. Its ECMAScript limitations.

How to apply this script to your algorithm

Firstly replace all slice to _ncSlice, substring to _ncSubstring, substr to _ncSubstr. Secondary lookup all typeof(yourExpr) == 'string' and Object.prototype.toString.call(yourExpr) == '[object String]' and add String._isNCString(yourExpr). Thats all

Links

lastest nonCopyingString.js unitTests split point calculation