Issue 410:  not the best optimization  
3 people starred this issue and may be notified of changes.  Back to list 
http://stackoverflow.com/questions/5565500/whydoesclosurecompilernotshortenthis used the closure compiler on http://closurecompiler.appspot.com/home
Apr 6, 2011
#1
schu...@gmail.com
Apr 6, 2011
For the record, here is the code in question: function f(a, b) { var start = Math.min(a, b); var end = Math.max(a, b); tb.selectionStart = start; tb.selectionEnd = end; }; In order to inline "end", the compiler needs to know two things: 1) that Math.max is sideeffect free (which it knows) 2) that the result of "Math.max" does not depend on global state (which it does not) This is a sideeffect free function: "Math.max = function() { return tb.selectionStart }" but with this definition of "Math.max" if "end" were to be inlined the value of tb.SelectionEnd would not be what is expected.
Apr 6, 2011
(No comment was entered for this change.)
Status:
Invalid
Apr 6, 2011
John, nice to know this is due to "global state" instead of sideeffects. These things get tricky! Now if it is certain that Math.max does not get redefined (i.e. it remains the internallyimplemented function), can the compiler then mark it as not depending on global state?
Apr 7, 2011
Maybe I'm just missing something, but I would also have expected this code in advanced mode to be inlined: var tb = {selectionStart: 0, selectionEnd: 0}; function f(a, b) { var start = Math.min(a, b); var end = Math.max(a, b); tb.selectionStart = start; tb.selectionEnd = end; } f(1, 12); window["tb"] = tb; Instead I get: var a = {selectionStart:0, selectionEnd:0}, b = Math.max(1, 12); a.selectionStart = Math.min(1, 12); a.selectionEnd = b; window.tb = a; In advanced, shouldn't the compiler be able to tell that Math.max doesn't depend on the global state?
Apr 8, 2011
For the simple cases, the infrastructure just isn't there yet. We special case "Math" already so it wouldn't be a stretch to special case it further. But in the general case we would need four things: * "Math" to be annotated or discovered to be "const" * "Math.min" to be annotated or discovered to be "const" * the function to be annotated with a "I don't don't have any dependencies on nonconst values or any const values that may not be initialized yet" * that values read by function can not be aliases of a affected value: The last one is a killer. Here are some obvious examples: function f(a, b) { var start = Math.min(a.selectionStart, b.selectionEnd); var end = Math.max(a.selectionStart, b.selectionEnd); tb.selectionStart = start; tb.selectionEnd = end; } or function f(a, b) { var start = Math.min(a, b); var end = Math.max(a, b); arguments[0] = start; arguments[1] = end; } 

► Sign in to add a comment 