Networkx: Nodes as Objects OR Nodes as ID's with Dictionary Attribute Tables
Question: Which is the most efficient in terms of memory management and computation
speed?

The simple test below suggests it is slightly better to store attributes
within nodes as a python object vs. dictionary lookups through attribute
tables. Will this always the case due to how the memory is allocated?

As a test I constructed a simple example:

    
    
    class country():
        def __init__(self, name, gdp):
            self.name = name
            self.gdp = gdp
        def __repr__(self):
            return str(self.name)
    
    #Country Objects
    countries = dict()
    countries['AUS'] = country('AUS', 2000)
    countries['USA'] = country('USA', 10000)
    countries['ZWE'] = country('ZWE', 13)
    
    #Attribute Dictionary
    gdp = dict()
    gdp['AUS'] = 2000
    gdp['USA'] = 10000
    gdp['ZWE'] = 13
    

Constructing Networks:

    
    
    #Nodes as ID's
    G1 = nx.Graph()
    G1.add_nodes_from(countries.keys())
    G1.nodes()
    
    #Nodes as Objects
    G2 = nx.Graph()
    for c in countries.keys():
        G2.add_node(countries[c])
    G2.nodes()
    

Running %timeit in IPython:

**G1f()**

    
    
    #Lookup Data from Strings Network
    def G1f():
        for n in G1.nodes():
            print "Node: %s" % n
            print "\tGDP: %s" % gdp[n]
    %timeit G1f
    

**Output for G1f():**

    
    
    10000000 loops, best of 3: 26.4 ns per loop
    

**G2f()**

    
    
    #Lookup Data from Objects 
    def G2f():
        for n in G2.nodes():
            print "Node: %s" % n.name
            print "\tGDP: %s" % n.gdp
    %timeit G2f 
    

**Output for G2f()**

    
    
    10000000 loops, best of 3: 21.8 ns per loop
    

* * *

**Updated**

**G3f() [from answers]**

    
    
    G3 = nx.Graph()
    for c,v in gdp.items():
        G3.add_node(c, gdp=v)
    def G3f():
        for n,d in G3.nodes(data=True):
            print "Node: %s" % n
            print "\tGDP: %s" % d['gdp']
    

**Output for G13f():**

    
    
    10000 loops, best of 3: 63 µs per loop
    


Answer: You could also use node attributes like this:

    
    
    import networkx as nx
    #Attribute Dictionary
    gdp = dict()
    gdp['AUS'] = 2000
    gdp['USA'] = 10000
    gdp['ZWE'] = 13
    
    G3 = nx.Graph()
    for c,v in gdp.items():
        G3.add_node(c, gdp=v)
    
    print G3.nodes(data=True)
    
    def G3f():
        for n,d in G3.nodes(data=True):
            print "Node: %s" % n
            print "\tGDP: %s" % d['gdp']
    

It's not clear to me the test timings are very significant. Unless this is a
very huge problem (maybe someday everyone will have their own country!) there
might not be much difference in speed or memory. I suspect that the overhead
of creating many small custom objects (country()) will end up using more
memory and time.

