How to use Node class of org.openqa.selenium.grid.node package

Best Selenium code snippet using org.openqa.selenium.grid.node.Node

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.node.config;
19
20import com.google.auto.service.AutoService;
21
22import com.beust.jcommander.Parameter;
23
24import org.openqa.selenium.grid.config.ConfigValue;
25import org.openqa.selenium.grid.config.HasRoles;
26import org.openqa.selenium.grid.config.NonSplittingSplitter;
27import org.openqa.selenium.grid.config.Role;
28
29import java.util.Collections;
30import java.util.HashSet;
31import java.util.List;
32import java.util.Set;
33
34import static org.openqa.selenium.grid.config.StandardGridRoles.NODE_ROLE;
35import static org.openqa.selenium.grid.node.config.NodeOptions.DEFAULT_DETECT_DRIVERS;
36import static org.openqa.selenium.grid.node.config.NodeOptions.DEFAULT_HEARTBEAT_PERIOD;
37import static org.openqa.selenium.grid.node.config.NodeOptions.DEFAULT_MAX_SESSIONS;
38import static org.openqa.selenium.grid.node.config.NodeOptions.DEFAULT_REGISTER_CYCLE;
39import static org.openqa.selenium.grid.node.config.NodeOptions.DEFAULT_REGISTER_PERIOD;
40import static org.openqa.selenium.grid.node.config.NodeOptions.DEFAULT_SESSION_TIMEOUT;
41import static org.openqa.selenium.grid.node.config.NodeOptions.NODE_SECTION;
42import static org.openqa.selenium.grid.node.config.NodeOptions.OVERRIDE_MAX_SESSIONS;
43
44@SuppressWarnings("unused")
45@AutoService(HasRoles.class)
46public class NodeFlags implements HasRoles {
47
48  @Parameter(
49    names = {"--max-sessions"},
50    description = "Maximum number of concurrent sessions. Default value is the number "
51                  + "of available processors.")
52  @ConfigValue(section = NODE_SECTION, name = "max-sessions", example = "8")
53  public int maxSessions = DEFAULT_MAX_SESSIONS;
54
55  @Parameter(
56    names = {"--override-max-sessions"},
57    arity = 1,
58    description = "The # of available processos is the recommended max sessions value (1 browser "
59                  + "session per processor). Setting this flag to true allows the recommended max "
60                  + "value to be overwritten. Session stability and reliability might suffer as "
61                  + "the host could run out of resources.")
62  @ConfigValue(section = NODE_SECTION, name = "override-max-sessions", example = "false")
63  public Boolean overrideMaxSessions = OVERRIDE_MAX_SESSIONS;
64
65  @Parameter(
66    names = {"--session-timeout"},
67    description = "Let X be the session-timeout in seconds. The Node will automatically kill "
68                  + "a session that has not had any activity in the last X seconds. " +
69                  "This will release the slot for other tests.")
70  @ConfigValue(section = NODE_SECTION, name = "session-timeout", example = "60")
71  public int sessionTimeout = DEFAULT_SESSION_TIMEOUT;
72
73  @Parameter(
74    names = {"--detect-drivers"}, arity = 1,
75    description = "Autodetect which drivers are available on the current system, " +
76                  "and add them to the Node.")
77  @ConfigValue(section = NODE_SECTION, name = "detect-drivers", example = "true")
78  public Boolean autoconfigure = DEFAULT_DETECT_DRIVERS;
79
80  @Parameter(
81    names = {"-I", "--driver-implementation"},
82    description = "Drivers that should be checked. If specified, will skip autoconfiguration. " +
83                  "Example: -I \"firefox\" -I \"chrome\"")
84  @ConfigValue(
85    section = NODE_SECTION,
86    name = "driver-implementation",
87    example = "[\"firefox\", \"chrome\"]")
88  public Set<String> driverNames = new HashSet<>();
89
90  @Parameter(
91    names = {"--driver-factory"},
92    description = "Mapping of fully qualified class name to a browser configuration that this " +
93                  "matches against. " +
94                  "--driver-factory org.openqa.selenium.example.LynxDriverFactory " +
95                  "'{\"browserName\": \"lynx\"}'",
96    arity = 2,
97    variableArity = true,
98    splitter = NonSplittingSplitter.class)
99  @ConfigValue(
100    section = NODE_SECTION,
101    name = "driver-factories",
102    example = "[\"org.openqa.selenium.example.LynxDriverFactory '{\"browserName\": \"lynx\"}']")
103  public List<String> driverFactory2Config;
104
105  @Parameter(
106    names = {"--grid-url"},
107    description = "Public URL of the Grid as a whole (typically the address of the Hub " +
108                  "or the Router)")
109  @ConfigValue(section = NODE_SECTION, name = "grid-url", example = "\"https://grid.example.com\"")
110  public String gridUri;
111
112  @Parameter(
113    names = {"--driver-configuration"},
114    description = "List of configured drivers a Node supports. " +
115                  "It is recommended to provide this type of configuration through a toml config " +
116                  "file to improve readability. Command line example: " +
117                  "--drivers-configuration name=\"Firefox Nightly\" max-sessions=2 " +
118                  "stereotype='{\"browserName\": \"firefox\", \"browserVersion\": \"86\", " +
119                  "\"moz:firefoxOptions\": " +
120                  "{\"binary\":\"/Applications/Firefox Nightly.app/Contents/MacOS/firefox-bin\"}}'",
121    arity = 3,
122    variableArity = true,
123    splitter = NonSplittingSplitter.class)
124  @ConfigValue(
125    section = NODE_SECTION,
126    name = "driver-configuration",
127    prefixed = true,
128    example = "\n" +
129              "name = \"Firefox Nightly\"\n" +
130              "max-sessions = 2\n" +
131              "stereotype = \"{\"browserName\": \"firefox\", \"browserVersion\": \"86\", " +
132              "\"moz:firefoxOptions\": " +
133              "{\"binary\":\"/Applications/Firefox Nightly.app/Contents/MacOS/firefox-bin\"}}\"")
134  public List<String> driverConfiguration;
135
136  @Parameter(
137    names = "--register-cycle",
138    description = "How often, in seconds, the Node will try to register itself for "
139                  + "the first time to the Distributor.")
140  @ConfigValue(section = NODE_SECTION, name = "register-cycle", example = "10")
141  public int registerCycle = DEFAULT_REGISTER_CYCLE;
142
143  @Parameter(
144    names = "--register-period",
145    description = "How long, in seconds, will the Node try to register to the Distributor for " +
146                  "the first time. After this period is completed, the Node will not attempt " +
147                  "to register again.")
148  @ConfigValue(section = NODE_SECTION, name = "register-period", example = "120")
149  public int registerPeriod = DEFAULT_REGISTER_PERIOD;
150
151  @Parameter(
152    names = "--heartbeat-period",
153    description = "How often, in seconds, will the Node send heartbeat events to the Distributor " +
154                  "to inform it that the Node is up.")
155  @ConfigValue(section = NODE_SECTION, name = "heartbeat-period", example = "10")
156  public int heartbeatPeriod = DEFAULT_HEARTBEAT_PERIOD;
157
158  @Override
159  public Set<Role> getRoles() {
160    return Collections.singleton(NODE_ROLE);
161  }
162}
163
Full Screen
copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.node.local;
19
20import com.google.common.collect.ImmutableList;
21import org.openqa.selenium.Capabilities;
22import org.openqa.selenium.WebDriverInfo;
23import org.openqa.selenium.grid.config.Config;
24import org.openqa.selenium.grid.docker.DockerOptions;
25import org.openqa.selenium.grid.log.LoggingOptions;
26import org.openqa.selenium.grid.node.Node;
27import org.openqa.selenium.grid.node.SessionFactory;
28import org.openqa.selenium.grid.node.config.DriverServiceSessionFactory;
29import org.openqa.selenium.grid.node.config.NodeOptions;
30import org.openqa.selenium.grid.server.BaseServerOptions;
31import org.openqa.selenium.grid.server.EventBusOptions;
32import org.openqa.selenium.grid.server.NetworkOptions;
33import org.openqa.selenium.remote.http.HttpClient;
34import org.openqa.selenium.remote.service.DriverService;
35import org.openqa.selenium.remote.tracing.Tracer;
36
37import java.util.ArrayList;
38import java.util.Collection;
39import java.util.List;
40import java.util.ServiceLoader;
41
42public class LocalNodeFactory {
43
44  public static Node create(Config config) {
45    LoggingOptions loggingOptions = new LoggingOptions(config);
46    EventBusOptions eventOptions = new EventBusOptions(config);
47    BaseServerOptions serverOptions = new BaseServerOptions(config);
48    NodeOptions nodeOptions = new NodeOptions(config);
49    NetworkOptions networkOptions = new NetworkOptions(config);
50
51    Tracer tracer = loggingOptions.getTracer();
52    HttpClient.Factory clientFactory = networkOptions.getHttpClientFactory(tracer);
53
54    LocalNode.Builder builder = LocalNode.builder(
55      tracer,
56      eventOptions.getEventBus(),
57      serverOptions.getExternalUri(),
58      nodeOptions.getPublicGridUri().orElseGet(serverOptions::getExternalUri),
59      serverOptions.getRegistrationSecret());
60
61    List<DriverService.Builder<?, ?>> builders = new ArrayList<>();
62    ServiceLoader.load(DriverService.Builder.class).forEach(builders::add);
63
64    nodeOptions.getSessionFactories(info -> createSessionFactory(tracer, clientFactory, builders, info))
65      .forEach((caps, factories) -> factories.forEach(factory -> builder.add(caps, factory)));
66
67    new DockerOptions(config).getDockerSessionFactories(tracer, clientFactory)
68      .forEach((caps, factories) -> factories.forEach(factory -> builder.add(caps, factory)));
69
70    return builder.build();
71  }
72
73  private static Collection<SessionFactory> createSessionFactory(
74    Tracer tracer,
75    HttpClient.Factory clientFactory,
76    List<DriverService.Builder<?, ?>> builders,
77    WebDriverInfo info) {
78    ImmutableList.Builder<SessionFactory> toReturn = ImmutableList.builder();
79
80    Capabilities caps = info.getCanonicalCapabilities();
81
82    builders.stream()
83      .filter(builder -> builder.score(caps) > 0)
84      .forEach(builder -> {
85        DriverService.Builder<?, ?> freePortBuilder = builder.usingAnyFreePort();
86        toReturn.add(new DriverServiceSessionFactory(
87          tracer,
88          clientFactory,
89          info.getCanonicalCapabilities(),
90          c -> freePortBuilder.score(c) > 0,
91          freePortBuilder));
92      });
93
94    return toReturn.build();
95  }
96}
97
Full Screen
copy
1public static void main(String[] args) {
2    List<Long> times = new ArrayList<>();
3    for (int i = 0; i < 100; i++) {
4        times.add(doIt());
5    }
6    System.out.println("avg = " + (times.stream().mapToLong(x -> x).average()));
7}
8
9static long doIt() {
10    long start = System.nanoTime();
11    List<Object> list = new LinkedList<>();
12    //uncomment line below to test with ArrayList
13    //list = new ArrayList<>();
14    for (int i = 0; i < 500; i++) {
15        list.add(i);
16    }
17
18    Iterator it = list.iterator();
19    while (it.hasNext()) {
20        it.next();
21        it.remove();
22    }
23    long end = System.nanoTime();
24    long diff = end - start;
25    //uncomment to see the JVM warmup and get faster for the first few iterations
26    //System.out.println(diff)
27    return diff;
28}
29
Full Screen
copy
1get                 O(1)
2add                 O(1)
3contains            O(n)
4next                O(1)
5remove              O(n)
6iterator.remove     O(n)
7
Full Screen
copy
1get                 O(n)
2add                 O(1)
3contains            O(n)
4next                O(1)
5remove              O(1)
6iterator.remove     O(1)
7
Full Screen
copy
1get                 O(1)
2add                 O(n)
3contains            O(n)
4next                O(1)
5remove              O(n)
6iterator.remove     O(n)
7
Full Screen
copy
1|---------------------|---------------------|--------------------|------------|
2|      Operation      |     ArrayList       |     LinkedList     |   Winner   |
3|---------------------|---------------------|--------------------|------------|
4|     get(index)      |       O(1)          |         O(n)       | ArrayList  |
5|                     |                     |  n/4 steps in avg  |            |
6|---------------------|---------------------|--------------------|------------|
7|      add(E)         |       O(1)          |         O(1)       | LinkedList |
8|                     |---------------------|--------------------|            |
9|                     | O(n) in worst case  |                    |            |
10|---------------------|---------------------|--------------------|------------|
11|    add(index, E)    |       O(n)          |         O(n)       | LinkedList |
12|                     |     n/2 steps       |      n/4 steps     |            |
13|                     |---------------------|--------------------|            |
14|                     |                     |  O(1) if index = 0 |            |
15|---------------------|---------------------|--------------------|------------|
16|  remove(index, E)   |       O(n)          |         O(n)       | LinkedList |
17|                     |---------------------|--------------------|            |
18|                     |     n/2 steps       |      n/4 steps     |            |
19|---------------------|---------------------|--------------------|------------|
20|  Iterator.remove()  |       O(n)          |         O(1)       | LinkedList |
21|  ListIterator.add() |                     |                    |            |
22|---------------------|---------------------|--------------------|------------|
23
24
25|--------------------------------------|-----------------------------------|
26|              ArrayList               |            LinkedList             |
27|--------------------------------------|-----------------------------------|
28|     Allows fast read access          |   Retrieving element takes O(n)   |
29|--------------------------------------|-----------------------------------|
30|   Adding an element require shifting | o(1) [but traversing takes time]  |
31|       all the later elements         |                                   |
32|--------------------------------------|-----------------------------------|
33|   To add more elements than capacity |
34|    new array need to be allocated    |
35|--------------------------------------|
36
Full Screen
copy
1Latency Comparison Numbers (~2012)
2----------------------------------
3L1 cache reference                           0.5 ns
4Branch mispredict                            5   ns
5L2 cache reference                           7   ns                      14x L1 cache
6Mutex lock/unlock                           25   ns
7Main memory reference                      100   ns                      20x L2 cache, 200x L1 cache
8Compress 1K bytes with Zippy             3,000   ns        3 us
9Send 1K bytes over 1 Gbps network       10,000   ns       10 us
10Read 4K randomly from SSD*             150,000   ns      150 us          ~1GB/sec SSD
11Read 1 MB sequentially from memory     250,000   ns      250 us
12Round trip within same datacenter      500,000   ns      500 us
13Read 1 MB sequentially from SSD*     1,000,000   ns    1,000 us    1 ms  ~1GB/sec SSD, 4X memory
14Disk seek                           10,000,000   ns   10,000 us   10 ms  20x datacenter roundtrip
15Read 1 MB sequentially from disk    20,000,000   ns   20,000 us   20 ms  80x memory, 20X SSD
16Send packet CA->Netherlands->CA    150,000,000   ns  150,000 us  150 ms
17
Full Screen
copy
1Operation                       ArrayList                      LinkedList  
2
3AddAll   (Insert)               101,16719                      2623,29291 
4
5Add      (Insert-Sequentially)  152,46840                      966,62216
6
7Add      (insert-randomly)      36527                          29193
8
9remove   (Delete)               20,56,9095                     20,45,4904
10
11contains (Search)               186,15,704                     189,64,981
12
Full Screen
copy
1import org.junit.Assert;
2import org.junit.Test;
3
4import java.util.*;
5
6public class ArrayListVsLinkedList {
7    private static final int MAX = 500000;
8    String[] strings = maxArray();
9
10    ////////////// ADD ALL ////////////////////////////////////////
11    @Test
12    public void arrayListAddAll() {
13        Watch watch = new Watch();
14        List<String> stringList = Arrays.asList(strings);
15        List<String> arrayList = new ArrayList<String>(MAX);
16
17        watch.start();
18        arrayList.addAll(stringList);
19        watch.totalTime("Array List addAll() = ");//101,16719 Nanoseconds
20    }
21
22    @Test
23    public void linkedListAddAll() throws Exception {
24        Watch watch = new Watch();
25        List<String> stringList = Arrays.asList(strings);
26
27        watch.start();
28        List<String> linkedList = new LinkedList<String>();
29        linkedList.addAll(stringList);
30        watch.totalTime("Linked List addAll() = ");  //2623,29291 Nanoseconds
31    }
32
33    //Note: ArrayList is 26 time faster here than LinkedList for addAll()
34
35    ///////////////// INSERT /////////////////////////////////////////////
36    @Test
37    public void arrayListAdd() {
38        Watch watch = new Watch();
39        List<String> arrayList = new ArrayList<String>(MAX);
40
41        watch.start();
42        for (String string : strings)
43            arrayList.add(string);
44        watch.totalTime("Array List add() = ");//152,46840 Nanoseconds
45    }
46
47    @Test
48    public void linkedListAdd() {
49        Watch watch = new Watch();
50
51        List<String> linkedList = new LinkedList<String>();
52        watch.start();
53        for (String string : strings)
54            linkedList.add(string);
55        watch.totalTime("Linked List add() = ");  //966,62216 Nanoseconds
56    }
57
58    //Note: ArrayList is 9 times faster than LinkedList for add sequentially
59
60    /////////////////// INSERT IN BETWEEN ///////////////////////////////////////
61
62    @Test
63    public void arrayListInsertOne() {
64        Watch watch = new Watch();
65        List<String> stringList = Arrays.asList(strings);
66        List<String> arrayList = new ArrayList<String>(MAX + MAX / 10);
67        arrayList.addAll(stringList);
68
69        String insertString0 = getString(true, MAX / 2 + 10);
70        String insertString1 = getString(true, MAX / 2 + 20);
71        String insertString2 = getString(true, MAX / 2 + 30);
72        String insertString3 = getString(true, MAX / 2 + 40);
73
74        watch.start();
75
76        arrayList.add(insertString0);
77        arrayList.add(insertString1);
78        arrayList.add(insertString2);
79        arrayList.add(insertString3);
80
81        watch.totalTime("Array List add() = ");//36527
82    }
83
84    @Test
85    public void linkedListInsertOne() {
86        Watch watch = new Watch();
87        List<String> stringList = Arrays.asList(strings);
88        List<String> linkedList = new LinkedList<String>();
89        linkedList.addAll(stringList);
90
91        String insertString0 = getString(true, MAX / 2 + 10);
92        String insertString1 = getString(true, MAX / 2 + 20);
93        String insertString2 = getString(true, MAX / 2 + 30);
94        String insertString3 = getString(true, MAX / 2 + 40);
95
96        watch.start();
97
98        linkedList.add(insertString0);
99        linkedList.add(insertString1);
100        linkedList.add(insertString2);
101        linkedList.add(insertString3);
102
103        watch.totalTime("Linked List add = ");//29193
104    }
105
106
107    //Note: LinkedList is 3000 nanosecond faster than ArrayList for insert randomly.
108
109    ////////////////// DELETE //////////////////////////////////////////////////////
110    @Test
111    public void arrayListRemove() throws Exception {
112        Watch watch = new Watch();
113        List<String> stringList = Arrays.asList(strings);
114        List<String> arrayList = new ArrayList<String>(MAX);
115
116        arrayList.addAll(stringList);
117        String searchString0 = getString(true, MAX / 2 + 10);
118        String searchString1 = getString(true, MAX / 2 + 20);
119
120        watch.start();
121        arrayList.remove(searchString0);
122        arrayList.remove(searchString1);
123        watch.totalTime("Array List remove() = ");//20,56,9095 Nanoseconds
124    }
125
126    @Test
127    public void linkedListRemove() throws Exception {
128        Watch watch = new Watch();
129        List<String> linkedList = new LinkedList<String>();
130        linkedList.addAll(Arrays.asList(strings));
131
132        String searchString0 = getString(true, MAX / 2 + 10);
133        String searchString1 = getString(true, MAX / 2 + 20);
134
135        watch.start();
136        linkedList.remove(searchString0);
137        linkedList.remove(searchString1);
138        watch.totalTime("Linked List remove = ");//20,45,4904 Nanoseconds
139    }
140
141    //Note: LinkedList is 10 millisecond faster than ArrayList while removing item.
142
143    ///////////////////// SEARCH ///////////////////////////////////////////
144    @Test
145    public void arrayListSearch() throws Exception {
146        Watch watch = new Watch();
147        List<String> stringList = Arrays.asList(strings);
148        List<String> arrayList = new ArrayList<String>(MAX);
149
150        arrayList.addAll(stringList);
151        String searchString0 = getString(true, MAX / 2 + 10);
152        String searchString1 = getString(true, MAX / 2 + 20);
153
154        watch.start();
155        arrayList.contains(searchString0);
156        arrayList.contains(searchString1);
157        watch.totalTime("Array List addAll() time = ");//186,15,704
158    }
159
160    @Test
161    public void linkedListSearch() throws Exception {
162        Watch watch = new Watch();
163        List<String> linkedList = new LinkedList<String>();
164        linkedList.addAll(Arrays.asList(strings));
165
166        String searchString0 = getString(true, MAX / 2 + 10);
167        String searchString1 = getString(true, MAX / 2 + 20);
168
169        watch.start();
170        linkedList.contains(searchString0);
171        linkedList.contains(searchString1);
172        watch.totalTime("Linked List addAll() time = ");//189,64,981
173    }
174
175    //Note: Linked List is 500 Milliseconds faster than ArrayList
176
177    class Watch {
178        private long startTime;
179        private long endTime;
180
181        public void start() {
182            startTime = System.nanoTime();
183        }
184
185        private void stop() {
186            endTime = System.nanoTime();
187        }
188
189        public void totalTime(String s) {
190            stop();
191            System.out.println(s + (endTime - startTime));
192        }
193    }
194
195
196    private String[] maxArray() {
197        String[] strings = new String[MAX];
198        Boolean result = Boolean.TRUE;
199        for (int i = 0; i < MAX; i++) {
200            strings[i] = getString(result, i);
201            result = !result;
202        }
203        return strings;
204    }
205
206    private String getString(Boolean result, int i) {
207        return String.valueOf(result) + i + String.valueOf(!result);
208    }
209}
210
Full Screen
copy
1Algorithm           ArrayList   LinkedList
2seek front            O(1)         O(1)
3seek back             O(1)         O(1)
4seek to index         O(1)         O(N)
5insert at front       O(N)         O(1)
6insert at back        O(1)         O(1)
7insert after an item  O(N)         O(1)
8
Full Screen
copy
1<build>
2    <plugins>
3        <plugin>
4            <groupId>org.apache.maven.plugins</groupId>
5            <artifactId>maven-compiler-plugin</artifactId>
6            <configuration>
7                <source>1.8</source>
8                <target>1.8</target>
9            </configuration>
10        </plugin>
11    </plugins>
12</build>
13
Full Screen
copy
1    <plugin>
2        <groupId>org.apache.maven.plugins</groupId>
3        <artifactId>maven-compiler-plugin</artifactId>
4        <configuration>
5            <source>1.8</source>
6            <target>1.8</target>
7        </configuration>
8    </plugin>
9
Full Screen
copy
1<bytecodeTargetLevel>
2  <module name="your_project_name_main" target="1.8" />
3  <module name="your_project_name_test" target="1.8" />
4</bytecodeTargetLevel>
5
Full Screen
copy
1android {
2  compileOptions {
3    ...
4    sourceCompatibility JavaVersion.VERSION_1_8
5    targetCompatibility JavaVersion.VERSION_1_8
6    ...
7   }
8}
9
Full Screen
copy
1<plugin>
2    <artifactId>maven-compiler-plugin</artifactId>
3    <version>2.3.2</version>
4        <configuration>
5            <source>1.8</source>
6            <target>1.8</target>
7            <encoding>UTF-8</encoding>
8        </configuration>
9</plugin>
10
Full Screen
copy
1<project>
2  [...]
3  <properties>
4    <maven.compiler.source>1.8</maven.compiler.source>
5    <maven.compiler.target>1.8</maven.compiler.target>
6  </properties>
7  [...]
8</project>
9
Full Screen
copy
1<project xmlns="http://maven.apache.org/POM/4.0.0"
2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
5<!-- ... -->
6
7    <build>
8        <plugins>
9            <plugin>
10                <groupId>org.apache.maven.plugins</groupId>
11                <artifactId>maven-compiler-plugin</artifactId>
12                <version>3.5.1</version>
13                <configuration>
14                    <source>1.8</source>
15                    <target>1.8</target>
16                </configuration>
17            </plugin>
18        </plugins>
19    </build>
20
21<!-- ... -->
22
23</project>
24
Full Screen
copy
1<build>
2    <plugins>
3        <plugin>
4            <groupId>org.apache.maven.plugins</groupId>
5            <artifactId>maven-compiler-plugin</artifactId>
6            <configuration>
7                <source>1.8</source>
8                <target>1.8</target>
9            </configuration>
10        </plugin>
11    </plugins>
12</build>
13
Full Screen
copy
1// CPP program to demonstrate processing
2// time of sorted and unsorted array
3#include <iostream>
4#include <algorithm>
5#include <ctime>
6using namespace std;
7
8const int N = 100001;
9
10int main()
11{
12    int arr[N];
13
14    // Assign random values to array
15    for (int i=0; i<N; i++)
16        arr[i] = rand()%N;
17
18    // for loop for unsorted array
19    int count = 0;
20    double start = clock();
21    for (int i=0; i<N; i++)
22        if (arr[i] < N/2)
23            count++;
24
25    double end = clock();
26    cout << "Time for unsorted array :: "
27        << ((end - start)/CLOCKS_PER_SEC)
28        << endl;
29    sort(arr, arr+N);
30
31    // for loop for sorted array
32    count = 0;
33    start = clock();
34
35    for (int i=0; i<N; i++)
36        if (arr[i] < N/2)
37            count++;
38
39    end = clock();
40    cout << "Time for sorted array :: "
41        << ((end - start)/CLOCKS_PER_SEC)
42        << endl;
43
44    return 0;
45}
46
Full Screen
copy
1Already sorted    32995 milliseconds
2Shuffled          125944 milliseconds
3
4Already sorted    18610 milliseconds
5Shuffled          133304 milliseconds
6
7Already sorted    17942 milliseconds
8Shuffled          107858 milliseconds
9
Full Screen
copy
1void run(vector<int>& v, const string& label)
2{
3    auto t0 = system_clock::now();
4    sort(v.begin(), v.end());
5    auto t1 = system_clock::now();
6    cout << label
7         << duration_cast<microseconds>(t1 — t0).count()
8         << " milliseconds\n";
9}
10
11void tst()
12{
13    vector<int> v(1'000'000);
14    iota(v.begin(), v.end(), 0);
15    run(v, "already sorted ");
16    std::shuffle(v.begin(), v.end(), std::mt19937{ std::random_device{}() });
17    run(v, "shuffled    ");
18}
19
Full Screen
copy
1#include <algorithm>
2#include <ctime>
3#include <iostream>
4
5int main() {
6    int data[32768]; const int l = sizeof data / sizeof data[0];
7
8    for (unsigned c = 0; c < l; ++c)
9        data[c] = std::rand() % 256;
10
11    // sort 200-element segments, not the whole array
12    for (unsigned c = 0; c + 200 <= l; c += 200)
13        std::sort(&data[c], &data[c + 200]);
14
15    clock_t start = clock();
16    long long sum = 0;
17
18    for (unsigned i = 0; i < 100000; ++i) {
19        for (unsigned c = 0; c < sizeof data / sizeof(int); ++c) {
20            if (data[c] >= 128)
21                sum += data[c];
22        }
23    }
24
25    std::cout << static_cast<double>(clock() - start) / CLOCKS_PER_SEC << std::endl;
26    std::cout << "sum = " << sum << std::endl;
27}
28
Full Screen
copy
1% Processing time with Sorted data vs unsorted data
2%==========================================================================
3% Generate data
4arraySize = 32768
5sum = 0;
6% Generate random integer data from range 0 to 255
7data = randi(256, arraySize, 1);
8
9
10%Sort the data
11data1= sort(data); % data1= data  when no sorting done
12
13
14%Start a stopwatch timer to measure the execution time
15tic;
16
17for i=1:100000
18
19    for j=1:arraySize
20
21        if data1(j)>=128
22            sum=sum + data1(j);
23        end
24    end
25end
26
27toc;
28
29ExeTimeWithSorting = toc - tic;
30
Full Screen
copy
1  a: Elapsed time (without sorting) = 3479.880861 seconds.
2  b: Elapsed time (with sorting ) = 2377.873098 seconds.
3
Full Screen
copy
1  a: Elapsed time (without sorting) = 19.8761 sec.
2  b: Elapsed time (with sorting ) = 7.37778 sec.
3
Full Screen
copy
1____________________________________________________________________________________
2- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
4
Full Screen
copy
1___________________________________________ Straight road
2 |_________________________________________|Longer road
3
Full Screen
copy
1 // sort backwards (higher values first), may be in some other part of the code
2 std::sort(data, data + arraySize, std::greater<int>());
3
4 for (unsigned c = 0; c < arraySize; ++c) {
5       if (data[c] < 128) {
6              break;
7       }
8       sum += data[c];               
9 }
10
Full Screen
copy
1MOV R0, #0   // R0 = sum = 0
2MOV R1, #0   // R1 = c = 0
3ADR R2, data // R2 = addr of data array (put this instruction outside outer loop)
4.inner_loop  // Inner loop branch label
5    LDRB R3, [R2, R1]   // R3 = data[c]
6    CMP R3, #128        // compare R3 to 128
7    ADDGE R0, R0, R3    // if R3 >= 128, then sum += data[c] -- no branch needed!
8    ADD R1, R1, #1      // c++
9    CMP R1, #arraySize  // compare c to arraySize
10    BLT inner_loop      // Branch to inner_loop if c < arraySize
11
Full Screen
copy
1if (expression)
2{
3    // Run 1
4} else {
5    // Run 2
6}
7
Full Screen
copy
1 O      Route 1  /-------------------------------
2/|\             /
3 |  ---------##/
4/ \            \
5                \
6        Route 2  \--------------------------------
7
Full Screen
copy
1bool a, b, c, d;
2if (a != 0) {
3    if (b != 0) {
4        c = 1;
5    }
6    else {
7        goto CFALSE;
8    }
9}
10else {
11    CFALSE:
12    c = 0;
13}
14if (a == 0) {
15    if (b == 0) {
16        d = 0;
17    }
18    else {
19        goto DTRUE;
20    }
21}
22else {
23    DTRUE:
24    d = 1;
25}
26
Full Screen
copy
1char a = 0, b = 1, c, d;
2c = a & b;
3d = a | b;
4
Full Screen
copy
1bool a; double x, y, z;
2a = x > y && z < 5.0;
3
Full Screen
copy
1if (likely( everything_is_ok ))
2{
3    /* Do something */
4}
5
Full Screen
copy
1if (unlikely(very_improbable_condition))
2{
3    /* Do something */    
4}
5
Full Screen
copy
1                        A) if (data[c] >= 128)
2                                /\
3                               /  \
4                              /    \
5                        true /      \ false
6                            /        \
7                           /          \
8                          /            \
9                         /              \
10              B) sum += data[c];          C) for loop or print().
11
Full Screen
copy
1int i= 0, j, k= arraySize;
2while (i < k)
3{
4  j= (i + k) >> 1;
5  if (data[j] >= 128)
6    k= j;
7  else
8    i= j;
9}
10sum= 0;
11for (; i < arraySize; i++)
12  sum+= data[i];
13
Full Screen
copy
1int i, k, j= (i + k) >> 1;
2for (i= 0, k= arraySize; i < k; (data[j] >= 128 ? k : i)= j)
3  j= (i + k) >> 1;
4for (sum= 0; i < arraySize; i++)
5  sum+= data[i];
6
Full Screen
copy
1// Test
2clock_t start = clock();
3long long a[] = {0, 0};
4long long sum;
5
6for (unsigned i = 0; i < 100000; ++i)
7{
8    // Primary loop
9    for (unsigned c = 0; c < arraySize; ++c)
10    {
11        int j = (data[c] >> 7);
12        a[j] += data[c];
13    }
14}
15
16double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
17sum = a[1];
18
Full Screen
copy
1// Declare and then fill in the lookup table
2int lut[256];
3for (unsigned c = 0; c < 256; ++c)
4    lut[c] = (c >= 128) ? c : 0;
5
6// Use the lookup table after it is built
7for (unsigned i = 0; i < 100000; ++i)
8{
9    // Primary loop
10    for (unsigned c = 0; c < arraySize; ++c)
11    {
12        sum += lut[data[c]];
13    }
14}
15
Full Screen
copy
1if (x < node->value)
2    node = node->pLeft;
3else
4    node = node->pRight;
5
Full Screen
copy
1i = (x < node->value);
2node = node->link[i];
3
Full Screen
copy
1for (int i = 0; i < max; i++)
2    if (condition)
3        sum++;
4
Full Screen
copy
1Condition                Pattern             Time (ms)
2-------------------------------------------------------
3(i & 0×80000000) == 0    T repeated          322
4
5(i & 0xffffffff) == 0    F repeated          276
6
7(i & 1) == 0             TF alternating      760
8
9(i & 3) == 0             TFFFTFFF…           513
10
11(i & 2) == 0             TTFFTTFF…           1675
12
13(i & 4) == 0             TTTTFFFFTTTTFFFF…   1275
14
15(i & 8) == 0             8T 8F 8T 8F …       752
16
17(i & 16) == 0            16T 16F 16T 16F …   490
18
Full Screen
copy
1for (int i = 0; i < array.Length; ++i)
2{
3   // Use array[i]
4}
5
Full Screen
copy
1// Generate data
2int arraySize = 32768;
3int[] data = new int[arraySize];
4
5Random random = new Random(0);
6for (int c = 0; c < arraySize; ++c)
7{
8    data[c] = random.Next(256);
9}
10
11/*To keep the spirit of the code intact, I'll make a separate lookup table
12(I assume we cannot modify 'data' or the number of loops)*/
13
14int[] lookup = new int[256];
15
16for (int c = 0; c < 256; ++c)
17{
18    lookup[c] = (c >= 128) ? c : 0;
19}
20
21// Test
22DateTime startTime = System.DateTime.Now;
23long sum = 0;
24
25for (int i = 0; i < 100000; ++i)
26{
27    // Primary loop
28    for (int j = 0; j < arraySize; ++j)
29    {
30        /* Here you basically want to use simple operations - so no
31        random branches, but things like &, |, *, -, +, etc. are fine. */
32        sum += lookup[data[j]];
33    }
34}
35
36DateTime endTime = System.DateTime.Now;
37Console.WriteLine(endTime - startTime);
38Console.WriteLine("sum = " + sum);
39Console.ReadLine();
40
Full Screen
copy
1==32551== Branches:        656,645,130  (  656,609,208 cond +    35,922 ind)
2==32551== Mispredicts:         169,556  (      169,095 cond +       461 ind)
3==32551== Mispred rate:            0.0% (          0.0%     +       1.2%   )
4
Full Screen
copy
1==32555== Branches:        655,996,082  (  655,960,160 cond +  35,922 ind)
2==32555== Mispredicts:     164,073,152  (  164,072,692 cond +     460 ind)
3==32555== Mispred rate:           25.0% (         25.0%     +     1.2%   )
4
Full Screen
copy
1          Bc    Bcm Bi Bim
2      10,001      4  0   0      for (unsigned i = 0; i < 10000; ++i)
3           .      .  .   .      {
4           .      .  .   .          // primary loop
5 327,690,000 10,016  0   0          for (unsigned c = 0; c < arraySize; ++c)
6           .      .  .   .          {
7 327,680,000 10,006  0   0              if (data[c] >= 128)
8           0      0  0   0                  sum += data[c];
9           .      .  .   .          }
10           .      .  .   .      }
11
Full Screen
copy
1          Bc         Bcm Bi Bim
2      10,001           4  0   0      for (unsigned i = 0; i < 10000; ++i)
3           .           .  .   .      {
4           .           .  .   .          // primary loop
5 327,690,000      10,038  0   0          for (unsigned c = 0; c < arraySize; ++c)
6           .           .  .   .          {
7 327,680,000 164,050,007  0   0              if (data[c] >= 128)
8           0           0  0   0                  sum += data[c];
9           .           .  .   .          }
10           .           .  .   .      }
11
Full Screen
copy
1 Performance counter stats for './sumtest_sorted':
2
3  11808.095776 task-clock                #    0.998 CPUs utilized          
4         1,062 context-switches          #    0.090 K/sec                  
5            14 CPU-migrations            #    0.001 K/sec                  
6           337 page-faults               #    0.029 K/sec                  
726,487,882,764 cycles                    #    2.243 GHz                    
841,025,654,322 instructions              #    1.55  insns per cycle        
9 6,558,871,379 branches                  #  555.455 M/sec                  
10       567,204 branch-misses             #    0.01% of all branches        
11
12  11.827228330 seconds time elapsed
13
Full Screen
copy
1 Performance counter stats for './sumtest_unsorted':
2
3  28877.954344 task-clock                #    0.998 CPUs utilized          
4         2,584 context-switches          #    0.089 K/sec                  
5            18 CPU-migrations            #    0.001 K/sec                  
6           335 page-faults               #    0.012 K/sec                  
765,076,127,595 cycles                    #    2.253 GHz                    
841,032,528,741 instructions              #    0.63  insns per cycle        
9 6,560,579,013 branches                  #  227.183 M/sec                  
10 1,646,394,749 branch-misses             #   25.10% of all branches        
11
12  28.935500947 seconds time elapsed
13
Full Screen
copy
1perf record -e branch-misses ./sumtest_unsorted
2perf annotate -d sumtest_unsorted
3
Full Screen
copy
1 Percent |      Source code & Disassembly of sumtest_unsorted
2------------------------------------------------
3...
4         :                      sum += data[c];
5    0.00 :        400a1a:       mov    -0x14(%rbp),%eax
6   39.97 :        400a1d:       mov    %eax,%eax
7    5.31 :        400a1f:       mov    -0x20040(%rbp,%rax,4),%eax
8    4.60 :        400a26:       cltq   
9    0.00 :        400a28:       add    %rax,-0x30(%rbp)
10...
11
Full Screen
copy
1for (unsigned i = 0; i < 100000; ++i)
2{
3    for (unsigned j = 0; j < arraySize; ++j)
4    {
5        if (data[j] >= 128)
6            sum += data[j];
7    }
8}
9
Full Screen
copy
1for (unsigned j = 0; j < arraySize; ++j)
2{
3    for (unsigned i = 0; i < 100000; ++i)
4    {
5        if (data[j] >= 128)
6            sum += data[j];
7    }
8}
9
Full Screen
copy
1for (unsigned j = 0; j < arraySize; ++j)
2{
3    if (data[j] >= 128)
4    {
5        for (unsigned i = 0; i < 100000; ++i)
6        {
7            sum += data[j];
8        }
9    }
10}
11
Full Screen
copy
1for (unsigned j = 0; j < arraySize; ++j)
2{
3    if (data[j] >= 128)
4    {
5        sum += data[j] * 100000;
6    }
7}
8
Full Screen
copy
1int max1(int a, int b) {
2    if (a > b)
3        return a;
4    else
5        return b;
6}
7
Full Screen
copy
1int max2(int a, int b) {
2    return a > b ? a : b;
3}
4
Full Screen
copy
1:max1
2    movl    %edi, -4(%rbp)
3    movl    %esi, -8(%rbp)
4    movl    -4(%rbp), %eax
5    cmpl    -8(%rbp), %eax
6    jle     .L2
7    movl    -4(%rbp), %eax
8    movl    %eax, -12(%rbp)
9    jmp     .L4
10.L2:
11    movl    -8(%rbp), %eax
12    movl    %eax, -12(%rbp)
13.L4:
14    movl    -12(%rbp), %eax
15    leave
16    ret
17
18:max2
19    movl    %edi, -4(%rbp)
20    movl    %esi, -8(%rbp)
21    movl    -4(%rbp), %eax
22    cmpl    %eax, -8(%rbp)
23    cmovge  -8(%rbp), %eax
24    leave
25    ret
26
Full Screen
copy
1T = branch taken
2N = branch not taken
3
4data[] = 0, 1, 2, 3, 4, ... 126, 127, 128, 129, 130, ... 250, 251, 252, ...
5branch = N  N  N  N  N  ...   N    N    T    T    T  ...   T    T    T  ...
6
7       = NNNNNNNNNNNN ... NNNNNNNTTTTTTTTT ... TTTTTTTTTT  (easy to predict)
8
Full Screen
copy
1data[] = 226, 185, 125, 158, 198, 144, 217, 79, 202, 118,  14, 150, 177, 182, ...
2branch =   T,   T,   N,   T,   T,   T,   T,  N,   T,   N,   N,   T,   T,   T  ...
3
4       = TTNTTTTNTNNTTT ...   (completely random - impossible to predict)
5
Full Screen
copy
1int t = (data[c] - 128) >> 31;
2sum += ~t & data[c];
3
Full Screen
copy
1public static void main(String[] args) {
2    List<Long> times = new ArrayList<>();
3    for (int i = 0; i < 100; i++) {
4        times.add(doIt());
5    }
6    System.out.println("avg = " + (times.stream().mapToLong(x -> x).average()));
7}
8
9static long doIt() {
10    long start = System.nanoTime();
11    List<Object> list = new LinkedList<>();
12    //uncomment line below to test with ArrayList
13    //list = new ArrayList<>();
14    for (int i = 0; i < 500; i++) {
15        list.add(i);
16    }
17
18    Iterator it = list.iterator();
19    while (it.hasNext()) {
20        it.next();
21        it.remove();
22    }
23    long end = System.nanoTime();
24    long diff = end - start;
25    //uncomment to see the JVM warmup and get faster for the first few iterations
26    //System.out.println(diff)
27    return diff;
28}
29
Full Screen
copy
1get                 O(1)
2add                 O(1)
3contains            O(n)
4next                O(1)
5remove              O(n)
6iterator.remove     O(n)
7
Full Screen
copy
1get                 O(n)
2add                 O(1)
3contains            O(n)
4next                O(1)
5remove              O(1)
6iterator.remove     O(1)
7
Full Screen
copy
1get                 O(1)
2add                 O(n)
3contains            O(n)
4next                O(1)
5remove              O(n)
6iterator.remove     O(n)
7
Full Screen
copy
1|---------------------|---------------------|--------------------|------------|
2|      Operation      |     ArrayList       |     LinkedList     |   Winner   |
3|---------------------|---------------------|--------------------|------------|
4|     get(index)      |       O(1)          |         O(n)       | ArrayList  |
5|                     |                     |  n/4 steps in avg  |            |
6|---------------------|---------------------|--------------------|------------|
7|      add(E)         |       O(1)          |         O(1)       | LinkedList |
8|                     |---------------------|--------------------|            |
9|                     | O(n) in worst case  |                    |            |
10|---------------------|---------------------|--------------------|------------|
11|    add(index, E)    |       O(n)          |         O(n)       | LinkedList |
12|                     |     n/2 steps       |      n/4 steps     |            |
13|                     |---------------------|--------------------|            |
14|                     |                     |  O(1) if index = 0 |            |
15|---------------------|---------------------|--------------------|------------|
16|  remove(index, E)   |       O(n)          |         O(n)       | LinkedList |
17|                     |---------------------|--------------------|            |
18|                     |     n/2 steps       |      n/4 steps     |            |
19|---------------------|---------------------|--------------------|------------|
20|  Iterator.remove()  |       O(n)          |         O(1)       | LinkedList |
21|  ListIterator.add() |                     |                    |            |
22|---------------------|---------------------|--------------------|------------|
23
24
25|--------------------------------------|-----------------------------------|
26|              ArrayList               |            LinkedList             |
27|--------------------------------------|-----------------------------------|
28|     Allows fast read access          |   Retrieving element takes O(n)   |
29|--------------------------------------|-----------------------------------|
30|   Adding an element require shifting | o(1) [but traversing takes time]  |
31|       all the later elements         |                                   |
32|--------------------------------------|-----------------------------------|
33|   To add more elements than capacity |
34|    new array need to be allocated    |
35|--------------------------------------|
36
Full Screen
copy
1Latency Comparison Numbers (~2012)
2----------------------------------
3L1 cache reference                           0.5 ns
4Branch mispredict                            5   ns
5L2 cache reference                           7   ns                      14x L1 cache
6Mutex lock/unlock                           25   ns
7Main memory reference                      100   ns                      20x L2 cache, 200x L1 cache
8Compress 1K bytes with Zippy             3,000   ns        3 us
9Send 1K bytes over 1 Gbps network       10,000   ns       10 us
10Read 4K randomly from SSD*             150,000   ns      150 us          ~1GB/sec SSD
11Read 1 MB sequentially from memory     250,000   ns      250 us
12Round trip within same datacenter      500,000   ns      500 us
13Read 1 MB sequentially from SSD*     1,000,000   ns    1,000 us    1 ms  ~1GB/sec SSD, 4X memory
14Disk seek                           10,000,000   ns   10,000 us   10 ms  20x datacenter roundtrip
15Read 1 MB sequentially from disk    20,000,000   ns   20,000 us   20 ms  80x memory, 20X SSD
16Send packet CA->Netherlands->CA    150,000,000   ns  150,000 us  150 ms
17
Full Screen
copy
1Operation                       ArrayList                      LinkedList  
2
3AddAll   (Insert)               101,16719                      2623,29291 
4
5Add      (Insert-Sequentially)  152,46840                      966,62216
6
7Add      (insert-randomly)      36527                          29193
8
9remove   (Delete)               20,56,9095                     20,45,4904
10
11contains (Search)               186,15,704                     189,64,981
12
Full Screen
copy
1import org.junit.Assert;
2import org.junit.Test;
3
4import java.util.*;
5
6public class ArrayListVsLinkedList {
7    private static final int MAX = 500000;
8    String[] strings = maxArray();
9
10    ////////////// ADD ALL ////////////////////////////////////////
11    @Test
12    public void arrayListAddAll() {
13        Watch watch = new Watch();
14        List<String> stringList = Arrays.asList(strings);
15        List<String> arrayList = new ArrayList<String>(MAX);
16
17        watch.start();
18        arrayList.addAll(stringList);
19        watch.totalTime("Array List addAll() = ");//101,16719 Nanoseconds
20    }
21
22    @Test
23    public void linkedListAddAll() throws Exception {
24        Watch watch = new Watch();
25        List<String> stringList = Arrays.asList(strings);
26
27        watch.start();
28        List<String> linkedList = new LinkedList<String>();
29        linkedList.addAll(stringList);
30        watch.totalTime("Linked List addAll() = ");  //2623,29291 Nanoseconds
31    }
32
33    //Note: ArrayList is 26 time faster here than LinkedList for addAll()
34
35    ///////////////// INSERT /////////////////////////////////////////////
36    @Test
37    public void arrayListAdd() {
38        Watch watch = new Watch();
39        List<String> arrayList = new ArrayList<String>(MAX);
40
41        watch.start();
42        for (String string : strings)
43            arrayList.add(string);
44        watch.totalTime("Array List add() = ");//152,46840 Nanoseconds
45    }
46
47    @Test
48    public void linkedListAdd() {
49        Watch watch = new Watch();
50
51        List<String> linkedList = new LinkedList<String>();
52        watch.start();
53        for (String string : strings)
54            linkedList.add(string);
55        watch.totalTime("Linked List add() = ");  //966,62216 Nanoseconds
56    }
57
58    //Note: ArrayList is 9 times faster than LinkedList for add sequentially
59
60    /////////////////// INSERT IN BETWEEN ///////////////////////////////////////
61
62    @Test
63    public void arrayListInsertOne() {
64        Watch watch = new Watch();
65        List<String> stringList = Arrays.asList(strings);
66        List<String> arrayList = new ArrayList<String>(MAX + MAX / 10);
67        arrayList.addAll(stringList);
68
69        String insertString0 = getString(true, MAX / 2 + 10);
70        String insertString1 = getString(true, MAX / 2 + 20);
71        String insertString2 = getString(true, MAX / 2 + 30);
72        String insertString3 = getString(true, MAX / 2 + 40);
73
74        watch.start();
75
76        arrayList.add(insertString0);
77        arrayList.add(insertString1);
78        arrayList.add(insertString2);
79        arrayList.add(insertString3);
80
81        watch.totalTime("Array List add() = ");//36527
82    }
83
84    @Test
85    public void linkedListInsertOne() {
86        Watch watch = new Watch();
87        List<String> stringList = Arrays.asList(strings);
88        List<String> linkedList = new LinkedList<String>();
89        linkedList.addAll(stringList);
90
91        String insertString0 = getString(true, MAX / 2 + 10);
92        String insertString1 = getString(true, MAX / 2 + 20);
93        String insertString2 = getString(true, MAX / 2 + 30);
94        String insertString3 = getString(true, MAX / 2 + 40);
95
96        watch.start();
97
98        linkedList.add(insertString0);
99        linkedList.add(insertString1);
100        linkedList.add(insertString2);
101        linkedList.add(insertString3);
102
103        watch.totalTime("Linked List add = ");//29193
104    }
105
106
107    //Note: LinkedList is 3000 nanosecond faster than ArrayList for insert randomly.
108
109    ////////////////// DELETE //////////////////////////////////////////////////////
110    @Test
111    public void arrayListRemove() throws Exception {
112        Watch watch = new Watch();
113        List<String> stringList = Arrays.asList(strings);
114        List<String> arrayList = new ArrayList<String>(MAX);
115
116        arrayList.addAll(stringList);
117        String searchString0 = getString(true, MAX / 2 + 10);
118        String searchString1 = getString(true, MAX / 2 + 20);
119
120        watch.start();
121        arrayList.remove(searchString0);
122        arrayList.remove(searchString1);
123        watch.totalTime("Array List remove() = ");//20,56,9095 Nanoseconds
124    }
125
126    @Test
127    public void linkedListRemove() throws Exception {
128        Watch watch = new Watch();
129        List<String> linkedList = new LinkedList<String>();
130        linkedList.addAll(Arrays.asList(strings));
131
132        String searchString0 = getString(true, MAX / 2 + 10);
133        String searchString1 = getString(true, MAX / 2 + 20);
134
135        watch.start();
136        linkedList.remove(searchString0);
137        linkedList.remove(searchString1);
138        watch.totalTime("Linked List remove = ");//20,45,4904 Nanoseconds
139    }
140
141    //Note: LinkedList is 10 millisecond faster than ArrayList while removing item.
142
143    ///////////////////// SEARCH ///////////////////////////////////////////
144    @Test
145    public void arrayListSearch() throws Exception {
146        Watch watch = new Watch();
147        List<String> stringList = Arrays.asList(strings);
148        List<String> arrayList = new ArrayList<String>(MAX);
149
150        arrayList.addAll(stringList);
151        String searchString0 = getString(true, MAX / 2 + 10);
152        String searchString1 = getString(true, MAX / 2 + 20);
153
154        watch.start();
155        arrayList.contains(searchString0);
156        arrayList.contains(searchString1);
157        watch.totalTime("Array List addAll() time = ");//186,15,704
158    }
159
160    @Test
161    public void linkedListSearch() throws Exception {
162        Watch watch = new Watch();
163        List<String> linkedList = new LinkedList<String>();
164        linkedList.addAll(Arrays.asList(strings));
165
166        String searchString0 = getString(true, MAX / 2 + 10);
167        String searchString1 = getString(true, MAX / 2 + 20);
168
169        watch.start();
170        linkedList.contains(searchString0);
171        linkedList.contains(searchString1);
172        watch.totalTime("Linked List addAll() time = ");//189,64,981
173    }
174
175    //Note: Linked List is 500 Milliseconds faster than ArrayList
176
177    class Watch {
178        private long startTime;
179        private long endTime;
180
181        public void start() {
182            startTime = System.nanoTime();
183        }
184
185        private void stop() {
186            endTime = System.nanoTime();
187        }
188
189        public void totalTime(String s) {
190            stop();
191            System.out.println(s + (endTime - startTime));
192        }
193    }
194
195
196    private String[] maxArray() {
197        String[] strings = new String[MAX];
198        Boolean result = Boolean.TRUE;
199        for (int i = 0; i < MAX; i++) {
200            strings[i] = getString(result, i);
201            result = !result;
202        }
203        return strings;
204    }
205
206    private String getString(Boolean result, int i) {
207        return String.valueOf(result) + i + String.valueOf(!result);
208    }
209}
210
Full Screen
copy
1Algorithm           ArrayList   LinkedList
2seek front            O(1)         O(1)
3seek back             O(1)         O(1)
4seek to index         O(1)         O(N)
5insert at front       O(N)         O(1)
6insert at back        O(1)         O(1)
7insert after an item  O(N)         O(1)
8
Full Screen
copy
1<build>
2    <plugins>
3        <plugin>
4            <groupId>org.apache.maven.plugins</groupId>
5            <artifactId>maven-compiler-plugin</artifactId>
6            <configuration>
7                <source>1.8</source>
8                <target>1.8</target>
9            </configuration>
10        </plugin>
11    </plugins>
12</build>
13
Full Screen
copy
1    <plugin>
2        <groupId>org.apache.maven.plugins</groupId>
3        <artifactId>maven-compiler-plugin</artifactId>
4        <configuration>
5            <source>1.8</source>
6            <target>1.8</target>
7        </configuration>
8    </plugin>
9
Full Screen
copy
1<bytecodeTargetLevel>
2  <module name="your_project_name_main" target="1.8" />
3  <module name="your_project_name_test" target="1.8" />
4</bytecodeTargetLevel>
5
Full Screen
copy
1android {
2  compileOptions {
3    ...
4    sourceCompatibility JavaVersion.VERSION_1_8
5    targetCompatibility JavaVersion.VERSION_1_8
6    ...
7   }
8}
9
Full Screen
copy
1<plugin>
2    <artifactId>maven-compiler-plugin</artifactId>
3    <version>2.3.2</version>
4        <configuration>
5            <source>1.8</source>
6            <target>1.8</target>
7            <encoding>UTF-8</encoding>
8        </configuration>
9</plugin>
10
Full Screen
copy
1<project>
2  [...]
3  <properties>
4    <maven.compiler.source>1.8</maven.compiler.source>
5    <maven.compiler.target>1.8</maven.compiler.target>
6  </properties>
7  [...]
8</project>
9
Full Screen
copy
1<project xmlns="http://maven.apache.org/POM/4.0.0"
2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
5<!-- ... -->
6
7    <build>
8        <plugins>
9            <plugin>
10                <groupId>org.apache.maven.plugins</groupId>
11                <artifactId>maven-compiler-plugin</artifactId>
12                <version>3.5.1</version>
13                <configuration>
14                    <source>1.8</source>
15                    <target>1.8</target>
16                </configuration>
17            </plugin>
18        </plugins>
19    </build>
20
21<!-- ... -->
22
23</project>
24
Full Screen