musictheory / NilScript

Objective-C-style language superset of JavaScript with a tiny, simple runtime
Other
50 stars 5 forks source link

Optimization: Don't call -[BaseObject init] #133

Open iccir opened 6 years ago

iccir commented 6 years ago

Assume the following code:

@implementation Foo

@property String name;

- (instancetype) initWithName:(String)name
{
    if ((self = [super init])) {
        _name = name;
    }
    return self;
}

- (Bar) makeBar
{
    return [[Bar alloc] init];
}

@end

@implementation Bar
@end

oj generates the following code:

$oj_oj._registerClass({$oj_c_Foo:1}, null, function($oj_s, $oj_m) { function $oj_c_Foo() { this.$oj_i_Foo$_name=null;this.constructor = $oj_c_Foo;this.$oj_id = ++$oj_oj._id;}

$oj_m.$oj_f_name = function() { return this.$oj_i_Foo$_name; } ; 

$oj_m.$oj_f_initWithName_ = function(name) 
{
    var self = this;if ((self = $oj_c_Foo.$oj_super.prototype.init.call(this))) {
        self.$oj_i_Foo$_name = name;
    }
    return self;
};

$oj_m.$oj_f_makeBar = function() 
{
    var $oj_t_0;return (($oj_t_0 = (new $oj_oj._cls.$oj_c_Bar())) && $oj_t_0.init());
};

return $oj_c_Foo;});

$oj_oj._registerClass({$oj_c_Bar:1}, null, function($oj_s, $oj_m) { function $oj_c_Bar() { this.constructor = $oj_c_Bar;this.$oj_id = ++$oj_oj._id;}return $oj_c_Bar;});

There are a few optimizations we can make here, based on the fact that -[BaseObject init] simply returns self.

-[Foo initWithName:] could be rewritten to:

$oj_m.$oj_f_initWithString_ = function(string) 
{
    self.$oj_i_Foo$_name = name;
    return self;
};

-[Foo makeBar] could be rewritten to:

$oj_m.$oj_f_makeBar = function() 
{
    return new $oj_oj._cls.$oj_c_Bar();
};

In practice, the performance improvement may be negligible. However, I'm trying to document all optimization ideas that I've been thinking about recently.