tclitcl

What method for constracting an object is more efficient?


I have a class that has several inner values:

private variable layer_type
private variable color
private variable name
private variable thickness
private variable conductivity
private variable permittivity
private variable loss_tangent

I want to initiate them with values that the user gives to the constructor, but since there 7 of them, to reduce clutter and code size I did it in a loop:

constructor {in_layer_type in_color in_conductivity in_loss_tangent in_name in_permittivity in_thikness f_row frame} {
    foreach var [list layer_type color conductivity loss_tangent name permittivity thikness] {
        set $var [set in_$var]
    }

Is there any difference (performance wise) with this approach, over the writing all the set commands?

set layer_type $in_layer_type
set color $in_color
#...
set thickness $in_thickness

Solution

  • In strict terms of efficiency, writing it all out in full is the most efficient method. I suggest that you don't do that! The problem is that it's difficult to maintain and hard to use (I don't know about you, but I hate calls with lots of mandatory positional arguments in all languages!) Instead, try something like this:

    constructor {f_row frame args} {
        foreach {var value} $args {
            if {[string match -* $var]} {
                set [string range $var 1 end] $value
            }
        }
        # ...
    }
    

    Yes, you need to write things a bit different to use this:

    TheClass theObjToMake $theFRow $theFrame -layer_type 12345 ...
    

    You're also advised to use Itcl's facilities for setting defaults if you're doing this. Pick something sensible and it will all suddenly seem very natural.