Size when a large subscript is specified for an array and a value is assigned

Sep 6, 2020 PHP JavaScript

Motivation

When developing a web application, when creating an array with the user ID (integer) as an index, isn’t it uselessly large? ??

Conclusion

If you use an array in PHP and Map in JavaScript, the size will not be unnecessarily large.

For PHP

There seems to be no problem even if you specify a large subscript.

$ array = [];
$ array [100] ='hoge';

echo count ($ array); // 1

For JavaScript

When a large subscript was specified, it became an array with empty inserted in the open space.

let array = [];
array [100] ='hoge';

console.log (array); // [empty x 100, "hoge"]
console.log (array.length); // 101

When I used Map, it behaved like an array in PHP.

let map = new Map ([[100,'hoge']]);

console.log (map); // Map (1) {100 => "hoge"}
console.log (map.size); // 1

What is the upper limit?

For PHP

The upper limit of the integer depends on the platform, and is about 2 billion or about 900 K. (Reference) In my environment, I was able to use up to 900 kyo (9 * 10 ^ 18).

$ array = [];
$ n = 9 * 10 ** 18;
$ array [$ n] ='hoge';

echo count ($ array); // 1

Even if there is a 900K user, it seems that it can be identified as a different user.

$ n = 9 * 10 ** 18;
$ m = $ n --1;
var_dump ($ n == $ m); // false

For JavaScript

There is a safe integer upper limit (2 ^ 53-1) and it is available in Number.MAX_SAFE_INTEGER (Reference/Number/MAX_SAFE_INTEGER)) The upper limit is smaller than PHP (~ 9.0 * 10 ^ 15) When using Map, there seems to be no problem if it is within this upper limit.

let n = Number.MAX_SAFE_INTEGER;
let map = new Map ([[n,'hoge']]);

console.log (map); // Map (1) {9007199254740991 => "hoge"}
console.log (map.size); // 1

let m = n --1;
console.log (n === m); // false