# This JavaScript implementation of range is fast. What are it's downsides?

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?

-

## migrated from stackoverflow.comNov 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.

-
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); }

-