2

I'm noticing that I have this line of code repeated in many different places in my code:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

First, I'm wondering the performance implications of this. For example, in my redrawing code which is called very often, I do that. Similarly, I may use JQuery to get a reference to the element.

I was wondering how big of a deal this was. I'm not exactly sure how to properly profile a website. I would like to somehow create a global reference to the context but when I try to do it in the global scope it doesn't run. Is the only way to have a function that lazily returns a reference to the canvas?

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • Hiya man, although I don't know the size of the project I would highly recommend to refactor the code and flow `DRY` throughout the code :) I have seen this first hand and the worst outcome of the people copy pasting JQ code (littered) in a big project :). In terms of performance yes it will definitely have a performance hit of you will call same line multiple time B-) http://stackoverflow.com/questions/400836/javascript-jquery-performance-measurement-and-best-practices-not-load-time this might come handy and it has link to top 25 tips, hope this helps, cheers! B-) – Tats_innit Jun 04 '12 at 04:00
  • Thanks for the useful link. Yeah, I try and follow DRY. These lines were the only ones not abiding to the rule and I'm not sure how to fix it. – Ryan Peschel Jun 04 '12 at 04:11

1 Answers1

4

Stop doing it in your drawing code immediately. Stop doing anything like that in your drawing code.

Save the context somewhere and pass the context in to your draw code (like in this five cent example I just made).

"Touching" the DOM is slow. Slooow. Any way you slice it. Do it as little as possible. This subject is talked about in depth in High Performance JavaScript by Zakas.

If you are concerned with JavaScript performance you should definitely give that title a look.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171