Home > Archive > Tcl > June 2007 > Which is faster?
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
| john_hughes@mentor.com 2007-06-05, 7:10 pm |
| Ok, I am looking at some code and trying to figure out which is
faster. We have a lot of legacy code
to where some C/C++ code talks to tcl like this:
string argStr;
for ( )
{
argStr = "part {" + partNumber + "}";
Tcl_AppendResult(interp, argStr.c_str(), NULL);
}
return TCL_OK;
We have newer code that looks like this:
Tcl_Obj* listPtr = Tcl_NewListObj( 0, NULL );
string argStr;
for ( )
{
argStr = "part {" + partNumber + "}";
Tcl_ListObjAppendElement( interp, listPtr,
Tcl_NewStringObj( argStr.c_str(), -1) );
}
Tcl_SetObjResult( interp, listPtr );
return TCL_OK;
It seems that the first example is pre 8.0 code and the 2nd example is
for 8.0
and later. And the 8.0 example is the preferred method, correct? And
theoretically
more efficient and such because of less type conversions, etc.
I my specific case, the amount of "stuff" being done inside the for
loop is immense, so I was
wondering if the 2nd example is less efficient (time wise) than the
old style code. Mainly due
to the number of calls to Tcl_NewStringObj() and
Tcl_ListObjAppendElement(). I know I can
profile the code to figure this out, but I thought you guys might save
me some time.
Thanks,
John
| |
| Ralf Fassel 2007-06-06, 7:22 pm |
| * john_hughes@mentor.com
| I my specific case, the amount of "stuff" being done inside the for
| loop is immense, so I was wondering if the 2nd example is less
| efficient (time wise) than the old style code. Mainly due to the
| number of calls to Tcl_NewStringObj() and
| Tcl_ListObjAppendElement().
The difference is how you use the result. The first form builds the
result as a string. If you use this later as a list, TCL converts it
to a list then, which delays the processing work to that later time.
The second form builds a list right now. If you use this as a list
later, the work is already done.
Possible improvements:
- c++ strings know their length, so pass argStr.size() instead of -1
as length argument for Tcl_NewStringObj() - saves one call to strlen().
If the list elements themselves are used as (sub-)lists:
- instead of manually building sublists using the + "{"+ "}" approach,
use real sublists:
Tcl_Obj *part = Tcl_NewStringObj("part", 4);
for () {
Tcl_Obj *sublist = Tcl_NewListObj( 1, &part );
Tcl_ListObjAppendElement(interp, sublist, Tcl_NewIntObj(partNumber));
Tcl_ListObjAppendElement( interp, listPtr, sublist);
}
Tcl_SetObjResult( interp, listPtr );
Note that I assume that the "{" "}" stuff is some manual
list-conversion left over from old-style TCL. If you really need the
"{}" in the data, you should keep the StringObj approach.
As always, error checking might be a good idea, too.
HTH
R'
| |
|
|
|
|
|
|
|