I have a 모델과 객체 걱정하지않아 서식하는 것으로 추정하고 있다. 나도 궁금 약간만이라도 어떤 하나의 개체를 저장하는 가장 효율적인 방법 및 검색 후 나는 # 39 시간은, s, s id. # 39 는 it& id& 숫자임.
그래서 내가 생각했던 그것은꿈의 2 옵션. s # 39 의 간단한 어레이에는 오버클로킹된 증가, 옵션 1 it& 색인입니다. 옵션 2 it& # 39 의 경우, 어쩌면 연관 배열을 객체를 유의해야 합니다. 어느 때 보다 효율적으로 내 질문은 내가 주로 하는 경우도 있지만, 단일 객체에는 읽어들이려면 루프 및 이를 통해 정렬.
옵션 1 개는 비사양 연관 배열:
var a = [{id: 29938, name: 'name1'},
{id: 32994, name: 'name1'}];
function getObject(id) {
for (var i=0; i < a.length; i++) {
if (a[i].id == id)
return a[i];
}
}
옵션 2 연관 배열:
var a = []; // maybe {} makes a difference?
a[29938] = {id: 29938, name: 'name1'};
a[32994] = {id: 32994, name: 'name1'};
function getObject(id) {
return a[id];
}
네, 저도 어레이에서는 사용하는 것이 두 번째 옵션은 질문이예요 빼냅니다 그래서 이 선언은 받아야 할 줄 두 번째 옵션은 다음과 같이 쓸 수 있다. var a = {}, 단 한 가지 문제는 '과' 입니다. 더 나은 성능을 가진 개체 지정하십시오. 읽어들이기를 특정 id: 여기서 어레이에서는 호스트였든 객체에는 id 가 핵심.
또한, 만약 내가 도움이 될 수 있을 것이라고 여러 차례 변경 오토메이티드 목록을 정렬하려면?
var a1 = [{id: 29938, name: 'name1'}, {id: 32994, name: 'name1'}];
var a2 = [];
a2[29938] = {id: 29938, name: 'name1'};
a2[32994] = {id: 32994, name: 'name1'};
var o = {};
o['29938'] = {id: 29938, name: 'name1'};
o['32994'] = {id: 32994, name: 'name1'};
for (var f = 0; f < 2000; f++) {
var newNo = Math.floor(Math.random()*60000+10000);
if (!o[newNo.toString()]) o[newNo.toString()] = {id: newNo, name: 'test'};
if (!a2[newNo]) a2[newNo] = {id: newNo, name: 'test' };
a1.push({id: newNo, name: 'test'});
}
! [테스트 설정이] [1] ! [테스트 결과] [2]
In your 질문이예요 몇 가지 오해
var a1 = [1, 2, 3];
var a2 = ["a", "b", "c"];
var a3 = [];
a3[0] = "a";
a3[1] = "b";
a3[2] = "c";
var a3 = [];
a3[29938] = "a";
a3[32994] = "b";
var a3 = {};
a3[29938] = "a";
a3[32994] = "b";
이 세 가지 가능성을 성능 테스트:
이 항목에서는 훌륭한 검토완료 http://support. 스매싱 저장실이: 먹어서나 고속 메모리 효율형 JavaScript
임의의 (숫자) 키 협력하였습니다 어레이이며 설정하려고 하면 정말 투명지에 성능 손실됩니다 windows용 행위 적 스토리지는 그 이후 모두 채워야 인덱스화합니다.
> foo = [];
[]
> foo[100] = 'a';
"a"
> foo
[undefined, undefined, undefined, ..., "a"]
sub> <; (참고로 어레이입니다 언약보다는 실제로 컨테인먼트하는 99 '정의되지 않은' 값뿐만 것 역할이 이렇게 이후 you& # 39, re 일부 지점에서 반복 [있어야] 이 어레이에는.) < /sub>;
그들이 어떻게 해야 이 두 가지 옵션을 위한 리터럴 아주 선택해제합니다 사용할 수 있습니다.
var arr = ['foo', 'bar', 'baz']; // no keys, not even the option for it
var obj = { foo : 'bar', baz : 42 }; // associative by its very nature
가장 강력한 ES6 매핑해야 사용할 수 있는 방법이 될 수 있다.
var myMap = new Map();
myMap.set(1, 'myVal');
myMap.set(2, { catName: 'Meow', age: 3 });
myMap.get(1);
myMap.get(2);
성능 및 시나리오 있지만브라우저에 따라 달라질 수 있습니다. 그런데 여기서 한 예로 '는' 가장 강력한 맵: https://jsperf.com/es6-map-vs-object-properties/2
const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;
//create data
for(var i=0;i<1000000;i++){
var getUnique = `${uniqueString()}`;
if(i===888555) seeking = getUnique;
arr.push(getUnique);
obj[getUnique] = true;
}
//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
if(arr[x]===seeking){
console.log('Array result:');
console.timeEnd('arrTimer');
break;
}
}
//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');
그 결과:
Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms
첫 번째 1 위 어레이입니다 / 객체에는 경우에도 ID 가 있다.
Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms
이 시도는 해봤는데 시행하십시오 다음 치수처리, 말 그대로.
주어진 2 차원 배열, 항상 같은 길이의 x 축과 y 축이 있는 것이 더 빠릅니다.
a) 2 차원 배열 및 찾는 중 첫 번째 인덱스화할 셀입니다 찾아볼 만들어, 그 뒤를 이어 두 번째 인덱스화하여 이리에:
var arr=[][]
var cell=[x][y]
또는
b) 문자열로 표현한 객체 생성 및 재동기화할 있는 이리에 obj, x, y 좌표, 단일 조회:
var obj={}
var cell = obj['x,y']
결과:. 알고보니 it& # 39 에 있는 두 개의 숫자 1 보다 훨씬 빠르게 할 수 있는 객체에 대한 속성 검색 인덱스를 어레이에는.
결과가 있습니다.
It 사용량에 따라 달라집니다. 이 사건은 조회 객체에는 경우 매우 가속화합니다.
이것은 프룬커 예제에서와 성능 및 객체에는 테스트하려면 어레이입니다 조회합니다.
https://plnkr.co/edit/n2expPWVmsdR3zmXvX4C? p = 미리봅니다
것을 볼 수 있습니다. 5.000 5.000 항목에 대한 찾는 길이 어레이입니다 수집, 시행하십시오 밀리스컨스 dl3000 '이상'
그러나 찾는 5.000 항목에 대한 속성, '2' 또는 '3' 밀리스컨스 5.000 객체에는 걸립니다
또한 큰 차이가 있어 객체에는 진단트리는 don& # 39 할 수 없다.
나는 이미 비슷한 문제를 갖고 있는 라이브 이벤트에서 평면가공 데릭쉐퍼드와 저장하였습니다 촛대를 소스 부족하십니까 x 로 할 수 있습니다. 내가 그 역할을 할 수 있는 각 객체에 저장됩니까 타임스탬프와 (키와 candle 양초 값으로 행위 자체를 할 수 있을 것 "이라고 말했다. 또다른 가능성을 그게 어떻게 할 수 있는 것처럼 각 항목을 는 어레이에서는 저장해야 한다. 여기서 한 가지 문제는 라이브 도래하도록하려하는 그들은 촛불을 렉시한테서 같은 컨트롤러상의 시간스탬프와 는 가장 최근의 데이터를 전송하는 최신 업데이트 업데이트 업데이트 때문에 기존 항목인지 새로 추가하기에서는 인컨텍스트 있습니다. 여기서는 모두 3 개의 결합할 수 있는 좋은 벤치마트 시도_횟수 가능성. 다음은 이상의 솔루션 어레이에는 4 배 이상 빠른 것으로 나타났다. Feel free to play
"use strict";
const EventEmitter = require("events");
let candleEmitter = new EventEmitter();
//Change this to set how fast the setInterval should run
const frequency = 1;
setInterval(() => {
// Take the current timestamp and round it down to the nearest second
let time = Math.floor(Date.now() / 1000) * 1000;
let open = Math.random();
let high = Math.random();
let low = Math.random();
let close = Math.random();
let baseVolume = Math.random();
let quoteVolume = Math.random();
//Clear the console everytime before printing fresh values
console.clear()
candleEmitter.emit("candle", {
symbol: "ABC:DEF",
time: time,
open: open,
high: high,
low: low,
close: close,
baseVolume: baseVolume,
quoteVolume: quoteVolume
});
}, frequency)
// Test 1 would involve storing the candle in an object
candleEmitter.on('candle', storeAsObject)
// Test 2 would involve storing the candle in an array
candleEmitter.on('candle', storeAsArray)
//Container for the object version of candles
let objectOhlc = {}
//Container for the array version of candles
let arrayOhlc = {}
//Store a max 30 candles and delete older ones
let limit = 30
function storeAsObject(candle) {
//measure the start time in nanoseconds
const hrtime1 = process.hrtime()
const start = hrtime1[0] * 1e9 + hrtime1[1]
const { symbol, time } = candle;
// Create the object structure to store the current symbol
if (typeof objectOhlc[symbol] === 'undefined') objectOhlc[symbol] = {}
// The timestamp of the latest candle is used as key with the pair to store this symbol
objectOhlc[symbol][time] = candle;
// Remove entries if we exceed the limit
const keys = Object.keys(objectOhlc[symbol]);
if (keys.length > limit) {
for (let i = 0; i < (keys.length - limit); i++) {
delete objectOhlc[symbol][keys[i]];
}
}
//measure the end time in nano seocnds
const hrtime2 = process.hrtime()
const end = hrtime2[0] * 1e9 + hrtime2[1]
console.log("Storing as objects", end - start, Object.keys(objectOhlc[symbol]).length)
}
function storeAsArray(candle) {
//measure the start time in nanoseconds
const hrtime1 = process.hrtime()
const start = hrtime1[0] * 1e9 + hrtime1[1]
const { symbol, time } = candle;
if (typeof arrayOhlc[symbol] === 'undefined') arrayOhlc[symbol] = []
//Get the bunch of candles currently stored
const candles = arrayOhlc[symbol];
//Get the last candle if available
const lastCandle = candles[candles.length - 1] || {};
// Add a new entry for the newly arrived candle if it has a different timestamp from the latest one we storeds
if (time !== lastCandle.time) {
candles.push(candle);
}
//If our newly arrived candle has the same timestamp as the last stored candle, update the last stored candle
else {
candles[candles.length - 1] = candle
}
if (candles.length > limit) {
candles.splice(0, candles.length - limit);
}
//measure the end time in nano seocnds
const hrtime2 = process.hrtime()
const end = hrtime2[0] * 1e9 + hrtime2[1]
console.log("Storing as array", end - start, arrayOhlc[symbol].length)
}
결론 여기에 10 은 제한값
Storing as objects 4183 nanoseconds 10
Storing as array 373 nanoseconds 10