|
Hello,
maybe reinventing the wheel, I needed a "perl like" join function in a
macro set, to build a string from an array and a separator.
So first I wrote this obvious function:
function join(array,sep)
{
str=""+array[0];
for(i=1;i<array.length;i++)
str=str+sep+array[i];
return str;
}
as in Java, with big arrays, it is not efficient to use a "+" operator
to concatenate strings in a long loop, rather use a StringBuffer append
method.
It seems to be the same with the IJ macro language, at least on OS X
10.5, using the String.buffer/String.append macro builtins is much
faster than the previous code.
this trick might be completely useless or already well known, but just
in case you need to output thousands of lines from various arrays in a
log/text file, I wanted to share...
regards,
sebastien
##########################################################
testmacro.txt
var ARRAY_SIZE=20000;
macro "testJoin2"
{
print("using join2 (with String.buffer)");
t0=getTime();
testArray=newArray(ARRAY_SIZE);
t1=getTime();
str=join2(testArray,"\t");
t2=getTime();
print(str);
t3=getTime();
print("length of returned string:"+lengthOf(str));
print("array creation:"+(t1-t0)+"ms");
print("joining:"+(t2-t1)+"ms");
print("printing:"+(t3-t2)+"ms");
}
macro "testJoin1"
{
print("using join1 (with + operator)");
t0=getTime();
testArray=newArray(ARRAY_SIZE);
t1=getTime();
str=join1(testArray,"\t");
t2=getTime();
print(str);
t3=getTime();
print("length of returned string:"+lengthOf(str));
print("array creation:"+(t1-t0)+"ms");
print("joining:"+(t2-t1)+"ms");
print("printing:"+(t3-t2)+"ms");
}
function join2(array,sep)
{
oldBuffer=String.buffer;
String.resetBuffer();
String.append(""+array[0]);
for(i=1;i<array.length;i++)
{
String.append(sep);
String.append(array[i]);
}
str=String.buffer;
String.resetBuffer();
String.append(oldBuffer);
return str;
}
function join1(array,sep)
{
str=""+array[0];
for(i=1;i<array.length;i++)
str=str+sep+array[i];
return str;
}
|