@@ -52,15 +52,15 @@ public PArray(Object clazz, Shape instanceShape, String formatStr, BufferFormat
52
52
this .formatStr = formatStr ;
53
53
this .format = format ;
54
54
this .lenght = 0 ;
55
- this .buffer = new byte [32 ];
55
+ this .buffer = new byte [0 ];
56
56
}
57
57
58
58
public PArray (Object clazz , Shape instanceShape , String formatStr , BufferFormat format , int length ) throws OverflowException {
59
59
super (clazz , instanceShape );
60
60
this .formatStr = formatStr ;
61
61
this .format = format ;
62
62
this .lenght = length ;
63
- this .buffer = new byte [Math . max ( 32 , PythonUtils .multiplyExact (length , format .bytesize ) )];
63
+ this .buffer = new byte [PythonUtils .multiplyExact (length , format .bytesize )];
64
64
}
65
65
66
66
public BufferFormat getFormat () {
@@ -84,12 +84,20 @@ public void setLenght(int lenght) {
84
84
this .lenght = lenght ;
85
85
}
86
86
87
+ private int computeNewSize (int newLength , int itemsize ) throws OverflowException {
88
+ // Overallocation using the same formula as CPython
89
+ int newSize = ((newLength >> 4 ) + (lenght < 8 ? 3 : 7 ) + newLength ) * itemsize ;
90
+ if (newSize / itemsize < newLength ) {
91
+ throw OverflowException .INSTANCE ;
92
+ }
93
+ return newSize ;
94
+ }
95
+
87
96
public void ensureCapacity (int newLength ) throws OverflowException {
88
97
assert newLength >= 0 ;
89
- // TODO better estimate
90
- int newSize = PythonUtils .multiplyExact (newLength , format .bytesize );
91
- if (newSize > buffer .length ) {
92
- byte [] newBuffer = new byte [newSize ];
98
+ int itemsize = format .bytesize ;
99
+ if (buffer .length / itemsize < newLength ) {
100
+ byte [] newBuffer = new byte [computeNewSize (newLength , itemsize )];
93
101
PythonUtils .arraycopy (buffer , 0 , newBuffer , 0 , buffer .length );
94
102
buffer = newBuffer ;
95
103
}
@@ -104,11 +112,9 @@ public void shift(int from, int by) throws OverflowException {
104
112
assert from >= 0 && from <= lenght ;
105
113
assert by >= 0 ;
106
114
int newLength = PythonUtils .addExact (lenght , by );
107
- // TODO better estimate
108
115
int itemsize = format .bytesize ;
109
- int newSize = PythonUtils .multiplyExact (newLength , itemsize );
110
- if (newSize > buffer .length ) {
111
- byte [] newBuffer = new byte [newSize ];
116
+ if (buffer .length / itemsize < newLength ) {
117
+ byte [] newBuffer = new byte [computeNewSize (newLength , itemsize )];
112
118
PythonUtils .arraycopy (buffer , 0 , newBuffer , 0 , from * itemsize );
113
119
PythonUtils .arraycopy (buffer , from * itemsize , newBuffer , (from + by ) * itemsize , (lenght - from ) * itemsize );
114
120
buffer = newBuffer ;
0 commit comments