簡體   English   中英

操縱和存儲巨大的有序列表或哈希的最佳方法是什么?

[英]What's the best way to manipulate and store huge ordered lists or hashes?

我有一個簡單的有序列表,可能包含一百萬個或更多的項目。 此列表僅執行了一些操作:

  • 在值中查找
  • 找到值的索引
  • 為索引尋找價值
  • 增值
  • 獲取列表中的項目數

將值添加到列表后,它永遠不會更改。 我將項目追加到列表中,沒有插入或刪除。

我需要操縱這個大列表,並將其持久存儲。 現在,我正在使用數據庫Int => String表示該列表,但是我認為應該有一種更有效的方法來執行此操作。

我可以使用memcached,但我認為缺少2個功能:

  • 持久存儲
  • 找到值的索引

看來您還需要一個String -> Int映射表。

在Perl中,最簡單的方法是將散列tie到DBM文件(請參閱man perltie )。

未經測試的示例代碼幾乎可以肯定得到改進:

use DB_File;
tie %value2index, 'DB_File', 'value2index';
tie %index2value, 'DB_File', 'index2value';

sub index_count() {
    return scalar %value2index;
}

sub value_exists() {
    my $value = shift;
    return exists($value2index{$value});
}

sub append() {
    my $value = shift;
    if (!value_exits($value)) { # prevent duplicate insertions
        my $index = index_count() + 1;
        $value2index{$value} = $index;
        $index2value{$index} = $value;
    }
}

sub find_index() {
    my $value = shift;
    return $value2index{$value};
}

sub find_value() {
    my $index = shift;
    return $index2value{$index};
}

不要在多線程環境中使用它,這里有非原子操作。

您的物品有多大? 您介意使用多少內存? 您的商品獨特嗎?

您可能會逃脫這樣的事情:

my @list; # This keeps the ordered list
my %keyval; # This maps key to value
my %valkey; # This maps value to key

在每個插入上,您將:

push @list, value;
$valkey{$value} = $#list;
$keyval{$#list} = $value;

並針對您的每個要求:

#Existence of a value:
if(exists($valkey{$value}));

#Existence of an index;
if(exists($keyval{$index}));

#value for an index:
$keyval{$index};

#value for a key:
$valkey{$value};

#Size
$#list; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM