Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This implementation of range() is very fast:

RANGE = []; for (var i=0; i<65536; ++i) RANGE.push(i-32768);
range = function(a,b){ return RANGE.slice(a+32768,b+32768); };

Are there downsides in using this approach?

share|improve this question

migrated from Nov 24 '12 at 22:27

This question came from our site for professional and enthusiast programmers.

Why are you subtracting 32k? – Šime Vidas Nov 23 '12 at 0:45
@ŠimeVidas To allow for negative ranges – Dokkat Nov 23 '12 at 0:46
@Dokkat: It might be more intuitive to run the loop from -32k to +32k – Bergi Nov 23 '12 at 2:05

relatively speaking-

1) its a bit heavy on the memory use, requiring the memory for a property + mem of a number for each integer in the possible range

2) always consumes the memory and cpu needed to intialize, even if the script never has use for it.

share|improve this answer
Interesting. 2 can be solved initializing the array only after the first use of range(); this would aggravate 1, though. – Dokkat Nov 23 '12 at 0:50
I don't think lazy loading it would have any significant effect on #1. – chris Nov 23 '12 at 0:56
+1. Lazy loading would just make the first invocation of range slower than the average implementation :-) – Bergi Nov 23 '12 at 2:04

Range could be declared as an Arraybuffer, which supports both method slice and an arrayview of just a part of the buffer without copying the data. Returning an arrayview would mitigate the problem of memory consumption and using typed array would use ~128k memory instead of 512k.

Also the function could possibly be self-modifying doing the initialization at the first call.

range = function(a,b) {  initialize_range;
        range = function(a,b) { return RANGE.slice(a,b) };
        return RANGE.slice(a,b); }
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.