google / google/closure-compiler

Object properties and methods are not optimised...

Open
#1,284 4 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

For example, if I want to make a graphics library with different renderpaths, the code doesn't gets optimised as I would expect from the closure compiler. I used the advanced mode.
# Example
## Original code

``` javascript
//Library part
/**
@const
*/
var Context_type_names=[
'HTML',
'Native'
];
/**
@constructor
@param {number} type
*/
function Canvas(type){
this.type=type;

if(type===0){
this.type0_root=document.body;
}
else{
var canvas=document.createElement('canvas');
document.body.appendChild(canvas);
this.type1_canvas_context=canvas.getContext('2d');
}

console.log(Context_type_names[type]+' canvas created.');
}

Canvas.prototype={
type:0,

//Body object
type0_root:null,

//Canvas object
type1_canvas_context:null,

paintRect:function(left,top,width,height){
if(this.type===0){
this.type0_root.innerHTML+='

';
}
else{
this.type1_canvas_context.fillRect(left,top,width,height);
}
}
}

//User part
var canvas=new Canvas(1);//Native target
canvas.paintRect(100,100,300,300);
```
## GCC result

``` javascript
var a=["HTML","Native"];function c(b){this.b=b;if(0===b)this.a=document.body;else{var d=document.createElement("canvas");document.body.appendChild(d);this.c=d.getContext("2d")}console.log(a[b]+" canvas created.")}c.prototype={b:0,a:null,c:null};var e=new c(1);0===e.b?e.a.innerHTML+='

':e.c.fillRect(100,100,300,300);
```
## Expected result

``` javascript
var a=document.createElement("canvas");document.body.appendChild(a);var b=a.getContext("2d");console.log("Native canvas created.");b.fillRect(100,100,300,300);
```

I expected this result because in the script were just one instance of this class: With type=1. So it is a constant. And since it is the only instance, there is no reason for keeping the class-instance structure. At the end, it works the same way with less code and RAM usage. And now, think about what will happen if one wants to create a very big library with thousands of lines per pseudo-type... At the end, these will not be just a few bytes too many...

What is the problem with it? Am I misunderstooding something about GCC?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.