Version 4 (modified by hopscc, 11 years ago) |
---|
StringBuilder
Cobra strings are immutable. To create something like a mutable string, use StringBuilder:
def visitMessage(url) as String sb = StringBuilder() sb.appendLine('Hello [.name],') sb.appendLine('Please visit [url].') s.append(' (Beware of the trolls).') # append without newline sep return sb.toString
If you would like to use explicit platform varying newlines in your code, try CobraCore.newLine which returns the newline specific to the current platform such as '\n' or '\r\n':
def visitMessage(url) as String nl = CobraCore.newLine sb = StringBuilder() sb.append('Hello [.name],[nl]') sb.append('Please visit [url].[nl]') return sb.toString
The vernacular notation is something like
sb = StringBuilder() seperator = '' for <someloop> value = ... some calc or marshalling sb.append(sep) sep = ',' # or whatever separator is between items sb.append(value) s = sb.toString # turn into a string for subsequent use
A note about performance
With string immutability and wrt .Net/C# conventional wisdom has it that use of a StringBuilder is faster/better performance wise than just catenating to a String type but it depends....
- True, StringBuilder append is 915-2000x faster than String append but for small strings the overhead of StringBuilder create (and conversion back to String) is much higher (150-180x) than just String create/append...
- Putting a single string in a StringBuilder is about 1.6x speed of String doing the same.
- i.e String append ( s='...' s+='...'... ) is FASTER than ( sb=StringBuilder('...' s.append('...' ... )
- create/append...2 strings in StringBuilder about same (1.02) speed of String doing same
- create/append...3,4 strings in StringBuilder faster (0.92, .8) speed than that of String doing same (Without conversion StringBuilder back to String)
Implies use String if appending <=2 strings, StringBuilder for more and using result directly
Full Cycle: create, append, convert to String
- create, convert to string - using String is about 200x faster than using a StringBuilder
- create, append 1 string, convert to String - String about 1.9x faster than StringBuilder
- conversion StringBuilder to String overhead is about 0.3
- create, append 2 strings, convert to String - using String about 1.13x faster than using StringBuilder
- create, append 3 strings, convert to String - using String about 1.2x faster than StringBuilder
- create, append 4 strings, convert to String - using String about same (.96, 1.04 slower) speed as using StringBuilder
- create, append 5 strings, convert to string - using String about 0.86 (1.2 slower) than StringBuilder
Implies that it is faster to use String if expecting to append <=4 strings, otherwise use a StringBuilder ...
For more information on the StringBuilder class, see Google(C# !StringBuilder)
See also: LibraryTopics