closure-compiler icon indicating copy to clipboard operation
closure-compiler copied to clipboard

Missed optimization: document.querySelector('') turns into var b=document;b.querySelector.call(b, '')

Open juj opened this issue 1 year ago • 2 comments

Input JS:

var buffer = new ArrayBuffer(1024);
var HEAPU8 = new Uint8Array(buffer);
var UTF8Decoder = new TextDecoder();

var UTF8ToString = (ptr, maxBytesToRead) => {
  if (!ptr) return '';
  var maxPtr = ptr + maxBytesToRead;
  for (var end = ptr; !(end >= maxPtr) && HEAPU8[end];) ++end;
  return UTF8Decoder.decode(HEAPU8.subarray(ptr, end));
};

function wgpu_canvas_get_webgpu_context(canvasSelector) {
  let canvas = document.querySelector(UTF8ToString(canvasSelector));
  let ctx = canvas.getContext('webgpu');
  return ctx;
}

wgpu_canvas_get_webgpu_context(0);

results in

'use strict';
var a=new ArrayBuffer(1024);
new Uint8Array(a);
new TextDecoder;
var b=document;
b.querySelector.call(b,"").getContext("webgpu");

The last two generated lines look odd. Instead, these two lines would be shorter as

'use strict';
var a=new ArrayBuffer(1024);
new Uint8Array(a);
new TextDecoder;
document.querySelector("").getContext("webgpu");

Online test

juj avatar Sep 04 '24 15:09 juj

(Lines 2-4 are also something that would be impactful to be able to manually annotate to Closure Compiler to optimize away.. this was discussed in https://github.com/google/closure-compiler/issues/3185 , I see these types of effectively redundant lines in Emscripten output for all users)

juj avatar Sep 04 '24 15:09 juj

Thanks for the report

rahul-kamat avatar Sep 11 '24 16:09 rahul-kamat